标签:val hlist ash for make private htable 散列 ret
public class SeparateChainingHashTable<T> { 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<T>(); } } public void insert(T val){ List<T> whichList=theLists[myhash(val)]; if(!whichList.contains(val)){ whichList.add(val); if(++currentSize>theLists.length){ rehash(); } } } public void makeEmpty(){ for(int i=0;i<theLists.length;i++){ theLists[i].clear(); } currentSize=0; } public void remove(T val){ List<T> whichList=theLists[myhash(val)]; if(whichList.contains(val)){ whichList.remove(val); currentSize--; } } public boolean contains(T val){ List<T> whichList=theLists[myhash(val)]; return whichList.contains(val); } private static final int DEFAULT_TABLE_SIZE=101; private List<T>[] theLists; private int currentSize; private void rehash(){ } private int myhash(T val){ int hashVal=val.hashCode(); hashVal%=theLists.length; if(hashVal<0){ hashVal+=theLists.length; } return hashVal; } private static int nextPrime(int n){ boolean state=isPrime(n); while(!state) { state=isPrime(++n); } return n; } private static boolean isPrime(int n){ if ( n==1 || n ==4 ) return false; if ( n ==2 || n== 3 ) return true; //num从5开始进入循环,以保证√n>=2,循环不会被跳过 for ( int i = 2; i<= Math.sqrt( n ); i++ ) { if ( n% i==0 ) return false; } return true; } }
标签:val hlist ash for make private htable 散列 ret
原文地址:http://www.cnblogs.com/wxw7blog/p/7608303.html