1. 程式人生 > 實用技巧 >Java1.7的HashMap原始碼分析-面試必備技能

Java1.7的HashMap原始碼分析-面試必備技能

  • HashMap是現在用的最多的map,HashMap的原始碼可以說是面試必備技能,今天我們試著分析一下jdk1.7下的原始碼。
  • 先說結論:陣列加連結串列

一、先看整體的資料結構

首先我們注意到資料是存放在一個Entry<K,V>陣列裡面,預設大小16.

public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
{ /**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 /**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30; /**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f; /**
* An empty table instance to share when the table is not inflated.
*/
static final Entry<?,?>[] EMPTY_TABLE = {}; /**
* The table, resized as necessary. Length MUST Always be a power of two.
*/
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE; ... ...

我們來看看Entry<K,V>長什麼樣

    static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
int hash; /**
* Creates new entry.
*/
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
} ... ...

這是一個單連結串列結構,next指向下一個

二、put方法

我們來解析一下最常用的put方法

public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
} modCount++;
addEntry(hash, key, value, i);
return null;
}

我們一步步來分析,首先如果table為空就初始化table

if (table == EMPTY_TABLE) {
inflateTable(threshold);
}

我們來看看inflateTable(threshold)方法,就是計算初始化的大小,初始化table.

    private void inflateTable(int toSize) {
// Find a power of 2 >= toSize
int capacity = roundUpToPowerOf2(toSize); threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
initHashSeedAsNeeded(capacity);
}

接著往下走,如果key是空的處理。

        if (key == null)
return putForNullKey(value);

進到putForNullKey()方法我們知道它是把null放到了table[0],for迴圈裡面是已經存在的資料進行替換;如果不存在,通過addEntry新增到table.

    private V putForNullKey(V value) {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);
return null;
}

回到put方法,往下走,獲取hash,通過hash獲取陣列的下標i

        int hash = hash(key);
int i = indexFor(hash, table.length);

接下來的for迴圈,是遍歷下標i的連結串列,比較key和hash,替換相應的value

        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}

for迴圈如果找到了,會把新值替換舊值,並返回oldvalue;

如果for迴圈沒找到,則通過addEntry()新增到table

    void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
} createEntry(hash, key, value, bucketIndex);
}

先進行擴容,如果需要,然後新增,把新元素新增到第一位,之前的往後排

    void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}

總結一下:

  • 先用key生成hash,定位到陣列的下標
  • 如果遍歷連結串列,查詢,找到之後替換,返回
  • 如果沒找到,把資料插入到第一位

三、get方法

get方法就簡單了

    public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key); return null == entry ? null : entry.getValue();
}

如果key為null,從第一位table[0]找

    private V getForNullKey() {
if (size == 0) {
return null;
}
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}

如果key不是null,走getEntry,基本就和put的邏輯反過來就行了

    final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
} 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;
}

通過key,計算hash,在計算陣列的下標i, 從連結串列的第一位開始,比較key和hash,一直往後遍歷,直到找到值,返回e;

最後,如果沒找到,返回null.

四、思考

  • 我們想一想,這個結構還有什麼問題嗎?
  • 如果hash演演算法不好,好多key都落在同一個下標,那麼連結串列是不是超長?
  • 我們改天說說java1.8是怎麼改進這個問題的。