//第一次写博客,java实现的灰常简单的HashTable
public class HashTable {
public HashTable(int n)
{
size = n;
capacity = 0;
array = new String[size];
}
public boolean putString(String str)
{
if(capacity >= size){
return false;
}
//获取索引
int index = hashStringToInt(str);
//简单的冲突处理方法,开放地址发->线性探测,找到空白位置
while( !isArrayEmpty(index) )
{
index = (index + 1) % size;
}
array[index] = str;
capacity++;
return true;
}
public boolean findString(String str)
{
int index = hashStringToInt(str);
while( array[index] != null && !array[index].equals(str) )
{
index = (index + 1) % size;
}
if( array[index] == null) return false;
return true;
}
//hash函数,最重要的函数了!
private int hashStringToInt(String str)
{
return Math.abs( str.hashCode() % size );
}
//测试使用函数
public void printHashCode(String str)
{
System.out.println(hashStringToInt(str));
}
private String array[] = null;
private int size = 0;
private int capacity = 0;
//返回array[index]是否已经被String占据
private boolean isArrayEmpty(int index)
{
if( null == array[index])
return true;
return false;
}
//测试用,无视之。。。
public static void printStringExits(HashTable ht, String s){
System.out.println(ht.findString(s));
}
public static void main(String args[])
{
HashTable ht = new HashTable(6);
//测试
String str1 = "this is a test1";
ht.printHashCode(str1);//2
String str2 = "好吧,,,我是汉语";
ht.printHashCode(str2);//4
String str3 = "被看穿了吗?";
ht.printHashCode(str3);//5
String str4 = "greeting from bupt";
ht.printHashCode(str4);//5--0
ht.putString(str1);
printStringExits(ht, str1);
ht.putString(str2);
printStringExits(ht, str2);
ht.putString(str3);
printStringExits(ht, str3);
ht.putString(str4);
printStringExits(ht, str4);
}
}