Copy Code code as follows:
public class hashtable{
Private string[] name; Key words
private int sum; Capacity
public static void Main (string[] args) {//test
HashTable ht = new HashTable ();
Ht.add ("Chenhaitao");
Ht.add ("Zhongcheng");
Ht.add ("Baiyudong");
Ht.add ("Huangshiyao");
Ht.add ("DJFLKD");
Ht.add ("GG");
System.out.println (Ht.contains ("Baiyudong"));
Ht.remove ("Huangshiyao");
System.out.println (Ht.contains ("Huangshiyao"));
Ht.print ();
}
Public HashTable () {//initialized, initial capacity is 10
name = new STRING[10];
sum = 0;
}
public int Hash1 (String s) {//hash function
Return Math.Abs (S.hashcode ())%name.length;
}
public int Hash2 (String s) {//handling conflicting hash functions
int result = Math.Abs (S.hashcode ())% (name.length-1);
System.out.println (s+ "--" +result);
if (result%2==0) {
return result + 1;
}
return result;
}
Public Boolean contains (string s) {//hash table contains string s
int start = HASH1 (s);
int i = start;
while (Name[i]!= null) {
if (Name[i].equals (s)) {
return true;
}
i = (i + HASH2 (s))%name.length;
if (i = = start) {
return false;
}
}
return false;
}
public void Add (String s) {
if (SUM>=NAME.LENGTH/2) {
This.rehash ();
}
int start = HASH1 (s);
int i = start;
while (Name[i]!= null) {
if (S.equals (Name[i])) {
Return
}
i = (i + HASH2 (s))%name.length;
if (i = = start) {
Return
}
}
Name[i] = s;
sum + +;
}
public void Rehash () {//expansion of a hash table is twice times the original, adding the original hash table to the new tables
HashTable ht = new HashTable ();
Ht.name = new string[this.name.length * 2];
for (int i = 0; i < this.name.length i + +) {
if ((This.name[i]!= null)) {
Ht.add (This.name[i]);
}
}
THIS.name = Ht.name;
This.sum = Ht.sum;
}
public void Remove (String s) {//delete an element
if (This.contains (s)) {
int i = This.getvalue (s);
This.name[i] = null;
}
}
public int GetValue (String s) {//Get S position in hash table
int start = THIS.HASH1 (s);
int i = start;
while (This.name[i]!= null) {
if (This.name[i].equals (s)) {
return i;
}
i = (i + THIS.HASH2 (s))%this.name.length;
if (i = = start) {
return-1;
}
}
return-1;
}
public void print () {//Output hash table all elements
for (int i = 0; i < name.length i + +) {
System.out.println (i+ ":" +name[i]);
}
}
public int size () {//hash table number of elements stored
return this.sum;
}
public int Length () {//hash table length
return this.name.length;
}
}