pro

pro



class Hashtable {

class Hash {

String key;

String data;

}


int capacity;

Hash tb[];


public Hashtable(int capacity) {

this.capacity = capacity;

tb = new Hash[capacity];

for (int i = 0; i < capacity; i++) {

tb[i] = new Hash();

}

}


private int hash(String str) {

int hash = 5381;


for (int i = 0; i < str.length(); i++) {

int c = (int) str.charAt(i);

hash = ((hash << 5) + hash) + c;

}

if (hash < 0)

hash *= -1;

return hash % capacity;

}


public String find(String key) {

int h = hash(key);

int cnt = capacity;

while (tb[h].key != null && (--cnt) != 0) {

if(isEquals(tb[h].key, key)){

return tb[h].data;

}

h = (h + 1) % capacity;

}

return null;

}


boolean add(String key, String data) {

int h = hash(key);

while (tb[h].key != null) {

if(isEquals(tb[h].key, key)){

return false;

}

h = (h + 1) % capacity;

}

tb[h].key = key;

tb[h].data = data;

return true;

}

boolean isEquals(String a, String b){

boolean isSame = false;

if(a.length()!=b.length())

return false;

for (int i = 0; i < a.length(); i++) {

if(a.charAt(i)==b.charAt(i))

continue;

else

return false;

}

return true;

}

}