package hash;
public class HashSet {
private static int maxsize=100;
public Node []hashtable;
private boolean []flagtable; // 0: no data; 1: data inside;
public HashSet(){
hashtable = new Node[maxsize];
flagtable = new boolean[maxsize];
for (int i=0;i<maxsize;i++)
flagtable[i]=false;
}
private static final int HashConv(String key){
// System.out.println(key+"'s hash is "+key.hashCode());
int i = (key.hashCode()) & (maxsize-1);
return i;
}
public boolean Insert(Node t){
int pos = HashConv(t.GetKey());
int cnt = 0;
boolean flag = false;
while(flagtable[pos]){
pos = ReHash(cnt,pos);
if(cnt==maxsize)
break;
cnt++;
}
if(!flagtable[pos])
{
hashtable[pos]=t;
flag = true;
flagtable[pos]=true;
}
return flag;
}
public int ReHash(int cnt,int pos){
pos = (pos + 1 + cnt*cnt)%(maxsize);
return pos;
}
public int Find(String key)
{
int pos = HashConv(key);
int mypos = -1;
int cnt = 0;
while(cnt != maxsize){
if(flagtable[pos] && key==hashtable[pos].GetKey()){
mypos = pos;
break;
}
else
{
pos = ReHash(cnt,pos);
cnt++;
}
}
//System.out.println(key+" is found at "+mypos);
return mypos;
}
public boolean Delete(String key){
int pos = Find(key);
if(-1==pos)
{
System.out.println("No Node with key "+key+" indside!");
return false;
}
else if (pos>=maxsize)
{
System.out.println("Node with key "+key+" in pos "+pos+" !\n Error!");
return false;
}
else{
flagtable[pos]=false;
System.out.println(key+" is deleted at "+pos);
return true;
}
}
public void Show(){
for (int i =0;i<maxsize;i++){
if(flagtable[i])
System.out.println(hashtable[i].GetKey()+" : "+hashtable[i].GetValue());
}
}
public static void main(String []args){
HashSet myhashset = new HashSet();
myhashset.Insert(new Node("ZhuGuanya",614));
myhashset.Insert(new Node("XuTingyu",647));
myhashset.Insert(new Node("YuXiaolong",675));
myhashset.Show();
int pos = myhashset.Find("ZhuGuanya");
System.out.println("ZhuGuanya is found at pos "+pos);
myhashset.Delete("Yuxiaolong");
myhashset.Delete("YuXiaolong");
myhashset.Delete("ZhuGuanya");
pos = myhashset.Find("ZhuGuanya");
System.out.println("ZhuGuanya is found at pos "+pos);
myhashset.Show();
}
}
package hash;
public class Node {
private String key;
private int value;
public Node()
{
key = "";
value = -1;
}
public Node(String i,int j)
{
key = i;
value = j;
}
public int GetValue()
{
return value;
}
public String GetKey()
{
return key;
}
public void SetValue(int value){
this.value = value;
}
public void SetKey(String key){
this.key = key;
}
}