解决散列表冲突的第一种方法通常叫做分离连接法,其做法是将散列到同一个值得所有元素保留到一个表中。我们可以使用标准库的实现方法。如果空间很紧,则更可取的方法是避免使用它们(因为这些表是双向链接的并且浪费空间)
下面给出一个例子:
package hash;
import java.util.LinkedList;
import java.util.List;
import java.util.Iterator;
import java.util.Random;
public class SeprateChainingHashTable<AnyType> {
private static final int DEFAULT_TABLE_SIZE=10;//默认容量
private List<AnyType>[] 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<AnyType>();
}
}
public void makeEmpty() {
for(List<AnyType>list:theLists){
list.clear();
}
currentSize=0;
}
public boolean contains(AnyType x){
List<AnyType> whichList =theLists[myhash(x)];
return whichList.contains(x);
}
public void insert(AnyType x) {
List<AnyType> whichList = theLists[myhash(x)];
if (!whichList.contains(x)) {
whichList.add(x);
if (++currentSize > theLists.length) {
rehash();
}
} else {
}
}
public void remove(AnyType x){
List<AnyType> 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<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 static boolean isPrime(int num){
if(num==2||num==3){
return true;
}
if(num==1||num%2==0){
return false;
}
for(int i=3;i*i<=num;i+=2){
if(num%i==0){
return false;
}
}
return true;
}
private int nextPrime(int num) {
// TODO Auto-generated method stub
if(num==0||num==1||num==2){
return 2;
}
if(num%2==0){
num++;
}
while (!isPrime(num)) {
num+=2;
}
return num;
}
public void printTable(){
for(int i=0;i<theLists.length;i++){
System.out.println("---------");
Iterator iterator=theLists[i].iterator();
while(iterator.hasNext()){
System.out.print(iterator.next()+"");
}
System.out.println();
}
}
public static void main(String[] args){
Random random=new Random();
SeprateChainingHashTable<Integer> hashTable=new SeprateChainingHashTable<Integer>();
for(int i=0;i<30;i++){
hashTable.insert(random.nextInt(30));
}
hashTable.printTable();
}
}
转载于:https://blog.51cto.com/13271983/2147835