必备知识:
什么是哈希表?
哈希表(Hash table,也叫散列表),是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫做散列表。
哈希表hashtable(key,value) 的做法其实很简单,就是把Key通过一个固定的算法函数既所谓的哈希函数转换成一个整型数字,然后就将该数字对数组长度进行取余,取余结果就当作数组的下标,将value存储在以该数字为下标的数组空间里
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 current;
}
}
/**
*
* @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 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(21);
if(entry != null) {
System.out.println("find the data:"+entry.data);
} else {
System.out.println("cann't find the data:"+null);
}
}