HashMap的存储结构:
属于连续存储空间和非连续存储空间结构的组合,数组的每一个元素存储一个hash,HashMap的代码片段:
/**
* Allocate a table of the given capacity and set the threshold accordingly.
* @param newCapacity must be a power of two
*/
private HashMapEntry<K, V>[] makeTable(int newCapacity) {
@SuppressWarnings("unchecked") HashMapEntry<K, V>[] newTable
= (HashMapEntry<K, V>[]) new HashMapEntry[newCapacity];
table = newTable;
threshold = (newCapacity >> 1) + (newCapacity >> 2); // 3/4 capacity
return newTable;
}
相同hash的不同value以链表结构存储,
void addNewEntry(K key, V value, int hash, int index) {
table[index] = new HashMapEntry<K, V>(key, value, hash, table[index]);
}
HashMapEntry的构造函数:
HashMapEntry(K key, V value, int hash, HashMapEntry<K, V> next) {
this.key = key;
this.value = value;
this.hash = hash;
this.next = next;
}
equal函数和hash的约定关系是:
equal为true,hash值必须相等;
hash值相等,equal未必为true,这就是hash冲突的情况;
如果违反这个约定,将会出现奇怪的逻辑现象,两个equal为true的对象,通过hashMap获取得到的值不一样,因为他们的hash值不同。