前言
在我年幼的时候, 一位高深莫测的程序员传授给我一份hashMap原理宝典.. 当时对这份宝典奉若神祗..但是!! 后来发现,那货给我讲的是错的!!!!
HashMap
HashMap在JDK1.8中做了重大改进 , 当每个桶上面节点大于8个时,会被转成树结构,本文先对旧版本的hashMap做一下研究 ,旧版本中,桶节点上面对应的都是单向链表
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 初始大小 16
static final int MAXIMUM_CAPACITY = 1 << 30; //最大容量
static final float DEFAULT_LOAD_FACTOR = 0.75f; //当超过0.75的时候扩容
从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;
}
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);
}
private static int roundUpToPowerOf2(int number) {
// assert number >= 0 : "number must be non-negative";
return number >= MAXIMUM_CAPACITY
? MAXIMUM_CAPACITY
: (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
}
当table == EMPTY_TABLE,调用inflateTable方法 对table进行扩充,扩充时又会调用roundUpToPowerOf2方法,roundUpToPowerOf2方法会返回最大容器或者1 或者 (number-1)*2, 可以看出 table是一个Entry数组
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;
}
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 Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
}
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) {
}
}
而Entity就是实际进行储存的对象 初始化table,判断key是不是空 然后对key进行hash,然后又对得出来的hash值进行了一次indexFor
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
return h & (length-1);
}
可以看出 是将h值进行与运算, 将该hash值应该放在entity[]的哪个index计算出来,然后
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;
}
}
如果该位置的Entry<K,V> e 不为null, 如果找到跟当前key的hash先更并且key也相等的e,将老值取出并返回,新值赋值,然后掉了一下recordAccess[在hashMap中 这个方法为空], 如果for循环并没有被执行,则
modCount++;
addEntry(hash, key, value, i);
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,value生成一个Entry放入到table[bucketIndex], 原来的值会成为新entity的next属性
put方法基本就是这样,对新增加的值进行hash,判断该值应该在table上面那个bucketIndex处,然后将该值放到此处,并将原来的值连接到该值上面
注意,同一个bucket上面entity链表中,所有的entity的key进行hash再进行indexFor值相同,并不是指相同的hash, 实际上,同一个key在hashMap中只会有一个entity
然后我们看get方法
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
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;
}
调用get方法之后,会先对key进行hash,然后对hash执行indexFor找出该key对应entity存放的bucket位置 取出该bucket位置上面的单向链表进行for循环,返回对应的entity
这样做有什么好处呢? 通过这种方式,我们可以迅速定位到key所在的链表,只对该条链表进行遍历即可
假如有100条数据,平均分散在10条链表上,普通的map需要对整个数据进行遍历;而hashMap只需要对一条准确的链表进行遍历,大大提高的查询速度
remove方法
public V remove(Object key) {
Entry<K,V> e = removeEntryForKey(key);
return (e == null ? null : e.value);
}
final Entry<K,V> removeEntryForKey(Object key) {
if (size == 0) {
return null;
}
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;
}
还是快速查找到对应的链表,如果该值在bucket上,则直接将该值移除,然后将该值的next放在bucket中,如果该值在链表中间,则将该值的上一个entity的next指向该值的next