哈希表,它相比於hashMap結構簡單點,它沒有涉及紅黑樹,直接使用鏈表的方式解決哈希衝突。java
咱們看它的字段,和hashMap差很少,使用table存放元素node
private transient Entry<?,?>[] table; private transient int count; private int threshold; private float loadFactor; private transient int modCount = 0;
它沒有常量字段,默認值是在構造方法裏面直接體現的,咱們看一下無參構造:數組
public Hashtable() { this(11, 0.75f); }
1.get()方法app
根據key得到value函數
public synchronized V get(Object key) { Entry<?,?> tab[] = table; //計算下標 int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; //遍歷查找,e=e.next for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { return (V)e.value; } } return null; }
2.put()方法this
與get()方法相似,也是遍歷table,而後調用addEntry()實現添加。code
public synchronized V put(K key, V value) { if (value == null) { throw new NullPointerException(); } Entry<?,?> tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; @SuppressWarnings("unchecked") Entry<K,V> entry = (Entry<K,V>)tab[index]; //若是已經存在,則覆蓋,返回老的值 for(; entry != null ; entry = entry.next) { if ((entry.hash == hash) && entry.key.equals(key)) { V old = entry.value; entry.value = value; return old; } } //不存在,直接添加 addEntry(hash, key, value, index); return null; }
addEntry()orm
private void addEntry(int hash, K key, V value, int index) { modCount++; Entry<?,?> tab[] = table; if (count >= threshold) { //大小超過閾值,要擴容 // Rehash the table if the threshold is exceeded rehash(); tab = table; hash = key.hashCode(); index = (hash & 0x7FFFFFFF) % tab.length; } //添加 @SuppressWarnings("unchecked") Entry<K,V> e = (Entry<K,V>) tab[index]; tab[index] = new Entry<>(hash, key, value, e); count++; }
注意這裏的手法,直接將新來的節點,放到頭部,這樣就能夠無論後面是否存在節點,都不會出現問題排序
protected Entry(int hash, K key, V value, Entry<K,V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; }
1.常量字段介紹ci
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 2的四次方,初始化默認的容量 static final int MAXIMUM_CAPACITY = 1 << 30; 最大的容量值 static final float DEFAULT_LOAD_FACTOR = 0.75f; //容量 負載因子, static final int TREEIFY_THRESHOLD = 8; //鏈表轉換爲數的閾值 static final int UNTREEIFY_THRESHOLD = 6; //樹轉壞爲鏈表的閾值 static final int MIN_TREEIFY_CAPACITY = 64; //桶中的數據採用紅黑樹存儲時,整個table的最小容量
字段:
transient Node<K,V>[] table; //存儲主幹,節點數組 transient Set<Map.Entry<K,V>> entrySet; transient int size; //元素數量 transient int modCount; //修改次數 //The next size value at which to resize (capacity * load factor). int threshold; //下一次擴容的大小, final float loadFactor; //負載因子
2.構造函數
2.1經常使用的無參構造:
默認構造方法,就直接給負載因子賦值,其餘沒有操做,其餘字段都是默認的。
// Constructs an empty <tt>HashMap</tt> with the default initial // capacity (16) and the default load factor (0.75). public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted }
2.2帶初始化容器大小,和負載因子的構造方法:
首先要判斷傳入參數的正確性,而後賦值。
public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; this.threshold = tableSizeFor(initialCapacity); }
2.3帶集合的構造方法:
傳入一個Map集合,調用put方法進行初始化。
public HashMap(Map<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); }
從上面的代碼中能夠看到,在構造方法中並無初始化table,具體的table初始化是在put操做上進行的。
3.添加
3.1 put()
是一個入口方法,實際調用的是putVal()方法,其中經過hash()方法計算了key對應的 值
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } //異或運算,保證存儲位置儘可能均勻分佈。 static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
具體的putVal()方法,內容很長
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; //變量初始化,n表示table的長度 if ((tab = table) == null || (n = tab.length) == 0) //容器初始化 n = (tab = resize()).length; //經過resize()方法獲取分配空間。 if ((p = tab[i = (n - 1) & hash]) == null) //若是新的位置是空的,則直接放入,否者要解決衝突 tab[i] = newNode(hash, key, value, null); //將value封裝成新的node else { //解決衝突 Node<K,V> e; K k; // 注意p的賦值在 第二個if裏面,它表示的是衝突位置所存放的節點。若是新傳入的節點和當前node的hash和key相同,則下面再處理 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode) //基於紅黑樹的插入 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { //基於鏈表的插入 for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } //更新當前傳入的值到當前node中。返回以前的oldValue if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; //修改次數+1, if (++size > threshold) //空間大小,若是超過了閾值,要擴容 resize(); afterNodeInsertion(evict); return null; }
其中涉及的重點方法:resize()方法,返回新分配的空間。
final Node<K,V>[] resize() { Node<K,V>[] oldTab = table;//獲取老的table空間 int oldCap = (oldTab == null) ? 0 : oldTab.length; //獲取老的容量 int oldThr = threshold; //獲取老的閾值 int newCap, newThr = 0; if (oldCap > 0) { if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } //擴容兩倍 else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } else if (oldThr > 0) // initial capacity was placed in threshold,構造函數指定了閾值 newCap = oldThr; else { // 第一次初始化 oldCap=0,oldThr=0 newCap = DEFAULT_INITIAL_CAPACITY; //默認大小,16 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //默認計算方法,16*0.75,12 } if (newThr == 0) { //初始化閾值 float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; //將新計算出來的值,賦值 @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; //從新分配空間。 table = newTab; //擴容後的空間賦值(此時,空間仍是空的) if (oldTab != null) { //若是老的空間,不是空的,那麼須要元素轉移 for (int j = 0; j < oldCap; ++j) { //遍歷進行轉移 Node<K,V> e; if ((e = oldTab[j]) != null) { //將元數取出來 oldTab[j] = null; if (e.next == null) newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order Node<K,V> loHead = null, loTail = null; Node<K,V> hiHead = null, hiTail = null; Node<K,V> next; do { next = e.next; if ((e.hash & oldCap) == 0) { if (loTail == null) loHead = e; else loTail.next = e; loTail = e; } else { if (hiTail == null) hiHead = e; else hiTail.next = e; hiTail = e; } } while ((e = next) != null); if (loTail != null) { loTail.next = null; newTab[j] = loHead; } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab; }
4.Node結構
static class Node<K,V> implements Map.Entry<K,V> { final int hash; //節點的hash值 final K key; //存入的key值 V value; //存放的值 Node<K,V> next; //下一個節點 .... }
注意hashMap和LinkedList的區別,後者是雙向的,而hashMap中的Node是單向的。
5.get()操做
public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; //代碼內容在這裏 }
調用getNode()方法,計算hash(key)值,經過Hash來得到node
final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 &&(first = tab[(n - 1) & hash]) != null) { //第一個 檢測數組中的hash定位得到第一個Node if (first.hash == hash &&((k = first.key) == key || (key != null && key.equals(k)))) return first; //第一個不是,那麼就是後續節點中,多是鏈表形式,多是紅黑樹 if ((e = first.next) != null) { if (first instanceof TreeNode) //若是是紅黑樹,經過getTreeNode()方法得到 return ((TreeNode<K,V>)first).getTreeNode(hash, key); //鏈表形式,直接循環遍歷得到。 do { if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; }
鏈表形式的獲取比較簡單,紅黑樹的得到,咱們放在下面紅黑樹單獨進行介紹。
TreeMap和以前的兩個map就不一樣了,它沒有使用哈希表,而是直接使用紅黑樹解決,它的字段只保存了根節點
private final Comparator<? super K> comparator; //排序比較器 private transient Entry<K,V> root; //根節點 private transient int size = 0; private transient int modCount = 0;
1.get()
public V get(Object key) { Entry<K,V> p = getEntry(key); return (p==null ? null : p.value); }
getEntry()
final Entry<K,V> getEntry(Object key) { // Offload comparator-based version for sake of performance if (comparator != null) return getEntryUsingComparator(key); if (key == null) throw new NullPointerException(); @SuppressWarnings("unchecked") Comparable<? super K> k = (Comparable<? super K>) key; Entry<K,V> p = root; while (p != null) { int cmp = k.compareTo(p.key); //左右分流 if (cmp < 0) p = p.left; else if (cmp > 0) p = p.right; else return p; } return null; }
2.put() 涉及紅黑樹的操做,因此代碼比較長
public V put(K key, V value) { Entry<K,V> t = root; if (t == null) { compare(key, key); // type (and possibly null) check root = new Entry<>(key, value, null); size = 1; modCount++; return null; } int cmp; Entry<K,V> parent; // split comparator and comparable paths Comparator<? super K> cpr = comparator; if (cpr != null) { do { parent = t; cmp = cpr.compare(key, t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); } else { if (key == null) throw new NullPointerException(); @SuppressWarnings("unchecked") Comparable<? super K> k = (Comparable<? super K>) key; do { parent = t; cmp = k.compareTo(t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); } Entry<K,V> e = new Entry<>(key, value, parent); if (cmp < 0) parent.left = e; else parent.right = e; fixAfterInsertion(e); size++; modCount++; return null; }
3.remove()
public V remove(Object key) { Entry<K,V> p = getEntry(key); if (p == null) return null; V oldValue = p.value; deleteEntry(p); //實際方法 return oldValue; }
HashMap表現得更像TreeMap和HashTable的結合體。
感謝你看到這裏,看完有什麼的不懂的能夠在評論區問我,以爲文章對你有幫助的話記得給我點個贊,天天都會分享java相關技術文章或行業資訊,歡迎你們關注和轉發文章!