/**
* @ClassName: HashTable
* @Description: TODO
* @author: huangyan
* @date:2017年12月22日 下午2:20:54
*/
public class HashTable {
private Entry[] table;
private int elements;
public HashTable() {
table = new Entry[16];
}
public HashTable(int size) {
table = new Entry[size];
}
/**
*
* @Title: insert
* @Description: 插入数据
* @param data
*/
public void insert(int data) {
Entry entry = new Entry(data);
int hash = (int) (hash(data) & (table.length-1));
if (null == (table[hash])) {
table[hash] = entry;
elements++;
} else {
Entry current = table[hash];
Entry parent = current;
while (current != null) {
parent = current;
current = current.next;
}
parent.next = entry;
elements++;
}
}
/**
*
* @Title: find
* @Description: 查找数据
* @param data
* @return
*/
public Entry find(int data) {
int hash = (int) (hash(data) & (table.length-1));
if (table[hash] == null) {
return null;
} else {
Entry current = table[hash];
while (current != null) {
if (current.data == data) {
return current;
}
current = current.next;
}
return null;
}
}
/**
*
* @Title: display
* @Description: 打印table中的数据
*/
public void display() {
Entry current = null;
for (int i = 0; i < table.length; i++) {
System.out.print("[" + i + "] ");
current = table[i];
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}
/**
*
* @Title: hash
* @Description: TODO
* @param key
* @return
*/
public long hash(int key){
return (key+"").hashCode();
}
/**
*
* @Title: size
* @Description: TODO
* @return
*/
public int size(){
return elements;
}
final static class Entry {
public int data;
public Entry next;
public Entry(){
}
public Entry(int data) {
this.data = data;
}
}
}
测试:
public class HashTableTest {
/**
* @Title: main
* @Description: TODO
* @param args
*/
public static void main(String[] args) {
List<Integer> arr = new ArrayList<Integer>();
HashTable table = new HashTable(16);
Random rand = new Random();
for(int i=0;i<30;i++) {
/*int data = rand.nextInt(100);
arr.add(data);*/
table.insert(i);
}
System.out.print("[");
for(int num :arr) {
System.out.print(((num+"").hashCode()& 15)+",");
}
System.out.println("]");
System.out.println(arr.toString());
table.display();
System.out.println("size:"+table.size());
System.out.println();
com.hashtable.HashTable.Entry entry = table.find(213);
if(entry != null) {
System.out.println("find the data:"+entry.data);
} else {
System.out.println("cann't find the data:"+null);
}
}
}