hash表的優缺點
hash表比樹形結構快的原因,表的是位置是計算出來的通過hash函數,滿足隨機插入的結構。但是在有該優點的情況下,需要考慮哈希衝突
本例結構中採用鏈地址法【在hash表的每一個表單元,都是鏈表結構,發生衝突的元素,自動加入鏈表】
在jdk8以前採用的是鏈表解決,在jdk8之後,在處理哈希衝突時,先採用鏈表,當鏈表中size大於8時,轉化爲樹形結構,採用的紅黑樹結構。
//不需要像二分搜索樹一樣 鍵值實現可比較,只需要能實現hashCode 但每一個對象都是繼承自Object 所以都有hashCode方法
public class HashTable<K, V> {
private final int[] capacity
= {53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593,
49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469,
12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741};
private static final int upperTol = 10;
private static final int lowerTol = 2;
private int CapacityIndex = 0;
private TreeMap<K, V>[] hashtable;
private int M;//設置哈希表數組長度,選擇一個合適的素數
private int size;//已經存儲的元素個數
public HashTable() {
this.M = capacity[CapacityIndex];
this.size = 0;
hashtable = new TreeMap[M];//只是開出了空間,還需要對每個空間進行實例化
for (int i = 0; i < M; i++) {
hashtable[i] = new TreeMap<>();
}
}
private int hash(K key) {
return (key.hashCode() & 0x7fffffff) % M;//消除掉key對應的hashCode的符號
}
public int getSize() {
return size;
}
public void add(K key, V value) {
TreeMap<K, V> map = hashtable[hash(key)];
if (map.containsKey(key)) {
map.put(key, value);
} else {
map.put(key, value);
size++;
}
//判斷數組越界問題
if (size >= upperTol * M && CapacityIndex + 1 < capacity.length) {
CapacityIndex++;
resize(capacity[CapacityIndex]);
}
}
public V remove(K key) {
TreeMap<K, V> map = hashtable[hash(key)];
V ret = null;
if (map.containsKey(key)) {
ret = map.remove(key);
size--;
}
if (size < lowerTol * M && CapacityIndex - 1 >= 0) {
CapacityIndex--;
resize(capacity[CapacityIndex]);
}
return ret;
}
public void set(K key, V value) {
TreeMap<K, V> map = hashtable[hash(key)];
if (!map.containsKey(key)) {
throw new IllegalArgumentException(key + "doesn't exist");
} else {
map.put(key, value);
}
}
public boolean contains(K key) {
return hashtable[hash(key)].containsKey(key);
}
public V get(K key) {
return hashtable[hash(key)].get(key);
}
private void resize(int newM) {
TreeMap<K, V>[] newHashTable = new TreeMap[newM];
for (int i = 0; i < newM; i++) {
newHashTable[i] = new TreeMap<>();
}
int oldM = M;
this.M = newM;//在hash()中會用到新的的M
//必須重新給M賦值!!!
for (int i = 0; i < oldM; i++) {
TreeMap<K, V> map = hashtable[i];
for (K key : map.keySet()) {
newHashTable[hash(key)].put(key, map.get(key));
}
}
this.hashtable = newHashTable;
}
}