import java.util.*;
/*
* 此散列表只对提供适当 equals 方法和返回一个 int 型量的 hashCode 方法的对象工作
*/
public class SeparateChainingHashTable<Type> {
private static final int DEFAULT_TABLE_SIZE = 5;
private List<Type> [] theLists;
private int currentSize; //插入的项数
private void rehash() {
List<Type> [] oldLists = theLists;
//创建一个两倍的表
theLists = new List[ 2 * theLists.length ];
for ( int i = 0; i < theLists.length; i++)
theLists[i] = new LinkedList<Type>();
//把旧表插入
currentSize = 0;
for ( int i = 0; i < oldLists.length; i++) {
for ( Type item : oldLists[i])
insert(item);
}
}
private int myhash( Type x ) {
int hashVal = x.hashCode();
hashVal %= theLists.length;
if ( hashVal < 0 )
hashVal += theLists.length;
return hashVal;
}
public SeparateChainingHashTable() {
this(DEFAULT_TABLE_SIZE);
}
public SeparateChainingHashTable( int size ) {
theLists = new LinkedList [ size ];
for ( int i = 0; i < theLists.length; i++) {
theLists[i] = new LinkedList<Type>();
}
}
public void insert( Type x ) {
List<Type> list = theLists[ myhash(x)];
if ( !list.contains(x) ) {
list.add(x);
if (++currentSize > 2 * theLists.length)
rehash();
}
}
public void remove( Type x ) {
List<Type> list = theLists[ myhash(x) ];
if ( list.contains(x)) {
list.remove(x);
currentSize--;
}
}
public boolean contains( Type x ) {
List<Type> list = theLists[ myhash(x) ];
return list.contains(x);
}
public void makeEmpty() {
for( int i = 0; i < theLists.length; i++)
theLists[i].clear();
currentSize = 0;
}
public void print() {
for(int i = 0; i < theLists.length; i++) {
System.out.print(i);
System.out.println(theLists[i]);
}
}
public static void main( String [] args ) {
Scanner scanner = new Scanner(System.in);
SeparateChainingHashTable<Employee> hashTable = new SeparateChainingHashTable<>();
System.out.println("请输入名字:");
String n = scanner.next();
while ( !n.equals("!") ) {
Employee employee = new Employee(n);
hashTable.insert(employee);
n = scanner.next();
}
hashTable.print();
scanner.close();
}
}
class Employee {
private String name;
public boolean equals( Object rhs ) {
return rhs instanceof Employee && name.equals( ( (Employee)rhs).name );
}
public int hashCode() {
return name.hashCode();
}
public Employee( String n ) {
name = n;
}
public String toString() {
return name;
}
}
输入
mike
job
hah
wow
sha
bob
haya
llo
leilei
niuniu
didi
!
输出
0[didi]
1[]
2[mike, leilei]
3[]
4[]
5[job, hah]
6[sha]
7[bob, llo]
8[niuniu]
9[wow, haya]