[Java]
Package changsheng. algorithms. hash;
Import java. util. Collections list;
Public class SeparateChainingHashTable <T> {
/**
* Construct the hash table.
*/
Public SeparateChainingHashTable (){
This (DEFAULT_TABLE_SIZE );
}
/**
* Construct the hash table.
*
* @ Param size
* Approximate table size.
*/Www.2cto.com
@ SuppressWarnings ("unchecked ")
Public SeparateChainingHashTable (int size ){
TheLists = (partition list <T> []) new partition list [nextPrime (size)];
For (int I = 0; I <theLists. length; I ++)
TheLists [I] = new member list <T> ();
}
/**
* Insert into the hash table. If the item is already present, then do
* Nothing.
*
* @ Param x
* The item to insert.
*/
Public void insert (T x ){
Partition list <T> whichList = theLists [x. hashCode () % theLists. length];
If (! WhichList. contains (x )){
WhichList. addFirst (x );
}
}
/**
* Remove from the hash table.
*
* @ Param x
* The item to remove.
*/
Public boolean remove (T x ){
Return theLists [x. hashCode () % theLists. length]. remove (x );
}
/**
* Find an item in the hash table.
*
* @ Param x
* The item to search.
* @ Return the matching item, or null if not found.
*/
Public boolean find (T x ){
Return theLists [x. hashCode () % theLists. length]. contains (x );
}
/**
* Make the hash table logically empty.
*/
Public void makeEmpty (){
For (int I = 0; I <theLists. length; I ++)
TheLists [I]. clear ();
}
Private static final int DEFAULT_TABLE_SIZE = 101;
/** The array of Lists .*/
Private partition list <T> [] theLists;
/**
* Internal method to find a prime number at least as large as n.
*
* @ Param n
* The starting number (must be positive ).
* @ Return a prime number larger than or equal to n.
*/
Private static int nextPrime (int n ){
If (n % 2 = 0)
N ++;
For (;! IsPrime (n); n + = 2)
;
Return n;
}
/**
* Internal method to test if a number is prime. Not an efficient algorithm.
*
* @ Param n
* The number to test.
* @ Return the result of the test.
*/
Private static boolean isPrime (int n ){
If (n = 2 | n = 3)
Return true;
If (n = 1 | n % 2 = 0)
Return false;
For (int I = 3; I * I <= n; I + = 2)
If (n % I = 0)
Return false;
Return true;
}
// Simple main
Public static void main (String [] args ){
SeparateChainingHashTable <Integer> H = new SeparateChainingHashTable <Integer> ();
Final int NUMS = 4000;
Final int GAP = 37;
System. out. println ("Checking... (no more output means success )");
For (int I = GAP; I! = 0; I = (I + GAP) % NUMS)
H. insert (new Integer (I ));
For (int I = 1; I <NUMS; I + = 2)
H. remove (new Integer (I ));
For (int I = 2; I <NUMS; I + = 2)
If (! H. find (new Integer (I )))
System. out. println ("Find fails" + I );
For (int I = 1; I <NUMS; I + = 2 ){
If (H. find (new Integer (I )))
System. out. println ("OOPS !!! "+ I );
}
}
}