解决散列表冲突的第一种方法通常叫做分离连接法,其做法是将散列到同一个值得所有元素保留到一个表中。我们可以使用标准库的实现方法。如果空间很紧,则更可取的方法是避免使用它们(因为这些表是双向链接的并且浪费空间)
下面给出一个例子:
package hash;

import java.util.LinkedList;
import java.util.List;
import java.util.Iterator;
import java.util.Random;

public class SeprateChainingHashTable {
private static final int DEFAULT_TABLE_SIZE=10;//默认容量
private List[] theLists;//散列表的数组
private int currentSize;//当前数据个数
public SeprateChainingHashTable(){
this(DEFAULT_TABLE_SIZE);
}
public SeprateChainingHashTable(int size) {
// TODO Auto-generated constructor stub
theLists = new LinkedList[nextPrime(size)];
for (int i = 0; i < theLists.length; i++) {
theLists[i] = new LinkedList();
}
}
public void makeEmpty() {
for(Listlist:theLists){
list.clear();
}
currentSize=0;
}
public boolean contains(AnyType x){
List whichList =theLists[myhash(x)];
return whichList.contains(x);
}
public void insert(AnyType x) {
List whichList = theLists[myhash(x)];
if (!whichList.contains(x)) {
whichList.add(x);
if (++currentSize > theLists.length) {
rehash();
}
} else {
}
}
public void remove(AnyType x){
List whichList = theLists[myhash(x)];
if(whichList.contains(x)){
whichList.remove(x);
currentSize--;
}else{

    }
}

private int myhash(AnyType x) {
    // TODO Auto-generated method stub
    int  hashVal=x.hashCode();
    hashVal%=theLists.length;
    if(hashVal<0){
        hashVal+=theLists.length;
    }
    return hashVal;
}
private void rehash() {
    // TODO Auto-generated method stub
    List[] oldLists=theLists;
    theLists=new List[nextPrime(2*theLists.length)];
    for(int j=0;j();
    }
    currentSize =0;
    for(int i=0;i hashTable=new SeprateChainingHashTable();
    for(int i=0;i<30;i++){
        hashTable.insert(random.nextInt(30));
    }
    hashTable.printTable();
}

}