1. 程式人生 > >HashMap原理

HashMap原理

size return table ble ans amp hashmap原理 tin key值

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 數組大小

static final float DEFAULT_LOAD_FACTOR = 0.75f; //負載因子

transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE; //數組

public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}

put方法,先hash key值,找到對應的buket位置,存放,如果hash值一樣,則用鏈表方式存儲,如果hash和key的equals一樣,則覆蓋

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;
}

get方法,先根據key獲取hash值,然後根據equals判斷,若不符合則循環鏈表

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;
}

resize 擴容的時候變成原來的2倍

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);
}

while (newCapacity < targetCapacity)
newCapacity <<= 1;
if (newCapacity > table.length)
resize(newCapacity);

HashMap原理