首先看我们通常使用的HashMap构造函数:
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
table = new Entry[DEFAULT_INITIAL_CAPACITY];
init();
}
方法init()是一个空方法,方法注释的第一句是“Initialization hook for subclasses.”,应该是跟子类交互的一个方法,既然是空方法,这里暂且不关注。
整个方法其实就只有一个作用table = new Entry[DEFAULT_INITIAL_CAPACITY];
就是用默认的参数初始化了一个Entry类型的数组,table是HashMap的一个成员变量transient Entry[] table;
从这里基本得出结论HashMap的结构基础是一个数组,既然它是Entry类型的,来看一下Entry的定义:
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
final int hash;
/**
* Creates new entry.
*/
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
public final K getKey() {
return key;
}
public final V getValue() {
return value;
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
Object k1 = getKey();
Object k2 = e.getKey();
if (k1 == k2 || (k1 != null && k1.equals(k2))) {
Object v1 = getValue();
Object v2 = e.getValue();
if (v1 == v2 || (v1 != null && v1.equals(v2)))
return true;
}
return false;
}
public final int hashCode() {
return (key==null ? 0 : key.hashCode()) ^
(value==null ? 0 : value.hashCode());
}
public final String toString() {
return getKey() + "=" + getValue();
}
/**
* This method is invoked whenever the value in an entry is
* overwritten by an invocation of put(k,v) for a key k that's already
* in the HashMap.
*/
void recordAccess(HashMap<K,V> m) {
}
/**
* This method is invoked whenever the entry is
* removed from the table.
*/
void recordRemoval(HashMap<K,V> m) {
}
}
大概可以看得出它有一个key和一个value,原来它就是键值对的容器,另外它还有一个指向自身类型的引用next,这似乎又跟链表扯上了关系。
到现在一切都还不清晰,知道数据基础是数组,又可能跟链表有关系。
理一下思路,目的是看数据结构,那看哪个方法可以窥探到数据结构呢?很显然 put(K key, V value)
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
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;
}
可以看到 方法通过键的hashCode()方法经过hash() indexFor()两个方法的转换得到了一个数组的索引i,通过下面的table[i]可以看出来,hash(),indexFor()方法如下:
static int hash(int h) {
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
/**
* Returns index for hash code h.
*/
static int indexFor(int h, int length) {
return h & (length-1);
}
这两个方法看得出来是比较精妙的,但是对于理解HashMap数据结构可以不用关注,我们只要知道,通过键的hashCode(),经过这两个方法处理可以获取一个数组的位置索引。
再看put方法中的for循环,e被初始化为数组上索引位置的元素,然后通过e.next()遍历,循环体的意思大概就是如果遍历到的Entry的key与要放入的key相同的,就把它的value替换成要放入的value,从这里分析可以得出数组上的table[i]应该是一个单向Entry链表的头
还没有完,如果for循环中没有进入if语句,也就是说没有遍历到的Entry都不满足key与要放入的key相同,这时候会执行addEntry(hash, key, value, i);看一下这个方法:
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
if (size++ >= threshold)
resize(2 * table.length);
}
Entry构造函数:
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
看addEntry,先取出的数组索引位置的Entry,也就是table[i],然后将要放入的key,value和这个table[i],作为参数构造了一个Entry,赋给了table[i],结果就是当前的table[i]存放了要放入的key和value,并且next指向了之前的table[i]。
想象一下从无到有的过程,很显然这就是一个链表,这样一来所有的猜想都被证实了,table[i]确实是一个链表的头,并且每当有新元素插入时候,这个位置都会被更新,原来的元素下移。
至此HashMap的数据结构已经清晰了,基础结构是一个数组,数组上的每一个位置又有一个链表,可以想象成葡萄架的形状。
HashMap的工作原理:
1 有hashCode可以通过static int hash(int h)、static int indexFor(int h, int length)定位到一个数组的索引位置,也就是一个链表的头。
2 在一个链表中,通过equals方法来判断是否是同一个key(上面的put(K key, V value)证实了这一点)。