散列的平方探测法实现
public class QuadraticProbingHashTable<T> { private static final int DEFAULT_TABLE_SIZE=10; private HashEntry<T>[] array; private int currentsize; public QuadraticProbingHashTable(){ this(DEFAULT_TABLE_SIZE); } public QuadraticProbingHashTable(int size){ allocateArray(size); makeEmpty(); } public void makeEmpty(){ currentsize=0; for(int i=0;i<array.length;i++){ array[i]=null; } } public boolean contain(T val){ int address=findPos(val); return isActive(address); } public void remove(T val){ int address=findPos(val); if(isActive(address)){ array[address].active=false; } currentsize--; } public void insert(T val){ int address=findPos(val); if((isActive(address))) return; array[address]=new HashEntry<T>(val, true); if(++currentsize>array.length/2){ rehash(); } } private static class HashEntry<T>{ public T val; public boolean active; public HashEntry(T val){ this(val,true); } public HashEntry(T val,boolean active){ this.val=val; this.active=active; } } private void allocateArray(int arraySize){ array=new HashEntry[nextPrime(arraySize)]; } private boolean isActive(int currentPos){ return array[currentPos]!=null&&array[currentPos].active; } private int findPos(T val){ int num=1; int currentnum=myhash(val); while(array[currentnum]!=null&&!array[currentnum].val.equals(val)){ currentnum+=num; num+=2; if(currentnum>array.length){ currentnum-=array.length; } } return currentnum; } private void rehash(){ } private int myhash(T val){ int t=val.hashCode()%array.length; if(t<0){ t+=array.length; } return t; } private static int nextPrime(int n){ if(isPrime(n)){ return n; } boolean b=false; while(!b){ n+=1; b=isPrime(n); } return n; } private static boolean isPrime(int n){ if(n==1&&n==3){ return true; } if(n==2&&n==4){ return false; } for(int i=5;i<= Math.sqrt( n ); i++){ if(n%i==0){ return false; } } return true; } }