分离链接法
public class SeparateChainingHashTable<AnyType> {
//构造器
public SeparateChainingHashTable(){
this(DEFAULT_TABLE_SIZE);
}
public SeparateChainingHashTable(int size){
theLists = new LinkedList[nextPrime(size)];
for(int i = 0; i < theLists.length; i++){
theLists[i] = new LinkedList<AnyType>();
}
}
public void insert(AnyType x){
List<AnyType> whichList = theLists[myhash(x)];
if(!whichList.contains(x)){
whichList.add(x);
if(++currentSize > theLists.length){
rehash();
}
}
}
public void remove(AnyType x){
List<AnyType> whichList = theLists[myhash(x)];
if(whichList.contains(x)){
whichList.remove(x);
currentSize--;
}
}
public boolean contains(AnyType x){
List<AnyType> whichList = theLists[myhash(x)];
return whichList.contains(x);
}
public void makeEmpty(){
for(int i = 0; i < theLists.length; i++){
theLists[i].clear();
}
currentSize = 0;
}
private static final int DEFAULT_TABLE_SIZE = 101;
private List<AnyType>[] theLists;
private int currentSize;
private void rehash(){
List<AnyType>[] oldLists = theLists;
theLists = new List[nextPrime(2*theLists.length)];
for(int j = 0; j < theLists.length; j++){
theLists[j] = new LinkedList<AnyType>();
}
currentSize = 0;
for(int i = 0; i < oldLists.length; i++){
for(AnyType item :oldLists[i]){
insert(item);
}
}
}
private int myhash(AnyType x){
//散列表只对遵守确定协议的那些对象工作,即这些对象:
//1, 必须提供适当equals方法
//2, 必须提供返回一个int型的hashCode方法
int hashVal = x.hashCode();
hashVal %= theLists.length;
if(hashVal < 0){
hashVal += theLists.length;
}
return hashVal;
}
private static int nextPrime(int n){
if(n%2 == 0){
n++;
}
for(; !isPrime(n); n+=2){
;
}
return n;
}
private static boolean isPrime(int n){
if(n == 2 || n ==3){
return true;
}
if(n == 1 || n%2 == 0){
return false;
}
return true;
}
}
未完待续