1. 程式人生 > >對HashMap一點認識

對HashMap一點認識

HashMap其實和Hashtable很像,僅有HashMap是執行緒不安全的和允許鍵值對為空這兩個不同。HashMap是無序的。

以下是原始碼裡面的解釋,

 implementation provides all of the optional map operations, and permits
 * <tt>null</tt> values and the <tt>null</tt> key.  (The <tt>HashMap</tt>
 * class is roughly equivalent to <tt>Hashtable</tt>, except that it is
 * unsynchronized and permits nulls.)  This class makes no guarantees as to
 * the order of the map; in particular, it does not guarantee that the order
 * will remain constant over time.

HashMap是以鍵值對的形式基於hash表的map實現。HashMap通過get(K)、put(K,V)方法來存取鍵值對,

當呼叫put()方法時,首先通過hashcode()方法返回一個hashcode用於找到bucket位置來儲存Entry物件,

Entry陣列相當於一個連結串列,當呼叫put的時候,新加的元素放到頭部,最先加的在尾部,如果bucket沒有元素就直接

放在頂部。

當呼叫get()方法時,首先通過hashcode找到bucket,然後通過KEY來找到對應的Entry,通過getEntry()方法獲取Entry,

final Entry<K,V> getEntry(Object key) {
        int hash = (key == null) ? 0 : hash(key);
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

通過equals方法找到該Entry,接著return一個Entry.getValue();如果KEY為空就返回一個null

如果Entry為空也返回null,否則返回對應的value。


HashMap有兩個引數影響其效能:初始容量和裝載因子,capacity是hash表裡面的bucket數量,初始容量就是當hash表

被建立的時候的容量裝載因子是其容量在自動增長之前可以達到多滿的尺度,當hash表中的Entry超過了裝載因子與容量

的乘積時,Hash表通過rehash來使容量加倍。預設的初始容量為16,預設的裝載因子為0.75;