前段时间参加面试,面试官问了基础的HashMap是如何实现的。虽然大致的答出来了,但是学了java这么久都没有认真的阅读一次HashMap的源码。这里写这篇文章仅仅作为学习积累之用。
首先来了解下HashMap的大致框架,HashMap中定义了一个数组table,table存放的元素的类型是Entry,数组中的每一个Entry都是链表头。当插入两个元素的时候,通过HashMap定义的hash方法获取两个Hashcode,根据Hashcode定位到它插入的数组位置。如果当前数组已经有元素了,那么从第一个元素开始遍历链表查找是否已经有这个元素,如果没有则将其插入到链表头部或者尾部。
上面提到的数组的大小,可以用户指定,也可以使用默认值。默认情况下这个值是DEFAULT_INITIAL_CAPACITY = 16。在你可以大致估算出HashMap中存放的元素数的时候,建议指定数组的大小,因为如果采用默认值, 并且插入的元素数远超过默认值的时候,会频繁的触发resize操作。所谓的resize操作是指扩大数组,将原有的元素复制到一个新的更大的数组中。
而触发的resize操作和threshold有密切关系,HashMap中存放的元素数目超过了threshold就会触发resize操作。而threshold的值与数组的大小以及负载因子loadFactor有关,threshold = capacity * loadFactor。在默认情况下loadFactor = 0.75,采用默认值的时候可以在时间和空间消耗达到一个较好的平衡。过大的loadFactor,也就是threshold十分接近capacity的时候,会导致查找时间较长,因为较多的元素被hash到同一个数组位置,组成较长的链表,从而导致遍历链表的时候时间较长。
上面大致讲了一下HashMap的实现原理,来看看代码层面的实现。
首先来看看HashMap的定义,
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
可以看到HashMap实现了Cloneable和Serializeble接口,表明HashMap可以进行克隆操作以及序列化。
HashMap中几个默认的常量值,
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 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;
分别对应的是默认的数组大小,数组最大大小,默认的负载因子。
而其构造函数是这样的,
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
// Find a power of 2 >= initialCapacity
// 2的n次方中大于initialCapacity的最小值,比如initialCapacity = 15,那么capacity = 16。
int capacity = 1;
while (capacity < initialCapacity)
capacity <<= 1;
this.loadFactor = loadFactor;
threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
useAltHashing = sun.misc.VM.isBooted() &&
(capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
init();
}
所做的操作包括
1)参数校验
2)初始化capacity,策略如注释所示。
3)初始化threshold
4)初始化table
添加元素的代码如下,
public V put(K key, V value) {
// 插入key为null元素
if (key == null)
return putForNullKey(value);
// 获取hash值
int hash = hash(key);
// 获取数组中位置
int i = indexFor(hash, table.length);
// 遍历链表
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
// key一样,则替换
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
// 添加entry
addEntry(hash, key, value, i);
return null;
}
其中的数组定位策略主要通过如下的两个方法实现,
/**
* Retrieve object hash code and applies a supplemental hash function to the
* result hash, which defends against poor quality hash functions. This is
* critical because HashMap uses power-of-two length hash tables, that
* otherwise encounter collisions for hashCodes that do not differ
* in lower bits. Note: Null keys always map to hash 0, thus index 0.
*/
final int hash(Object k) {
int h = 0;
if (useAltHashing) {
if (k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h = hashSeed;
}
h ^= k.hashCode();
// 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);
}
可以看到index最后的实现和length有关系,也就是当length改变的时候,index也会相应改变,所以当resize操作发生时,会重新定位。
正是由于前面说到的capacity一定是2的n次方,所以h & (length - 1) == h % (length),所以其定位的位置一定是0-capacity。同时,由于位运算在实际的运算中是十分高效的,所以使用h & (length - 1) == h % length可以带来性能的提升。
元素的最终插入是通过addEntry方法实现,
void addEntry(int hash, K key, V value, int bucketIndex) {
// resize操作
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
// 创建entry
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++;
}
entry的构造函数,
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
可以看到table[bucketIndex] = new Entry<>(hash, key, value, e),将数组中对应的位置设置为新插入的元素,然后通过entry构造函数中的next = n,将这个新的元素的next设置为原始的对应位置的元素。这样就实现了元素插入到链表头的操作。
上面介绍了插入操作,下面介绍删除操作。
final Entry<K,V> removeEntryForKey(Object key) {
int hash = (key == null) ? 0 : hash(key);
int i = indexFor(hash, table.length);
Entry<K,V> prev = table[i];
Entry<K,V> e = prev;
while (e != null) {
Entry<K,V> next = e.next;
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
modCount++;
size--;
if (prev == e)
table[i] = next;
else
prev.next = next;
e.recordRemoval(this);
return e;
}
prev = e;
e = next;
}
return e;
}
删除操作主要也就是通过遍历链表然后删除操作,没有什么太多说的。
resize是HashMap中比较重要的一个操作,其实现主要通过transfer实现,
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
通过上面的代码可以看出,transfer方法逐渐遍历原有的元素,并将其反向插入到链表中。
e.next = newTable[i]; newTable[i] = e; e = next,每一个元素都被插入到链表头,所以与之前的链表是反向的。
而正是由于这个操作,引发了HashMap在高并发的情况下出现死循环的情况。
具体情况可以参看这篇文章

43万+

被折叠的 条评论
为什么被折叠?



