HashMap本质数据加链表。根据key取得hash值,然后计算出数组下标,如果多个key对应到同一个下标,就用链表串起来,新插入的在前面。
HashMap是线程不安全的里面的方法都是没有加synchronizated非线程安全方法
1.HashMap的数据结构
HashMap的底层是用数组+单链表实现的
这个采用的是连接表法,数组相当于,单链表的表头
第一步:根据key算出hashcode
第二步:根据hashcode 转换成内存中的地址,再根据这个内存地址找到对应的数组的下标
第三步: 如果数据对应的下标没有冲突,直接取值,如果有多个对应这个数组下标,遍历这个数组下标对应 的单链表,根据key去匹配单链表中Entry<K,V>值
源码:
/**
* An empty table instance to share when the table is not inflated.
*/
static final Entry<?,?>[] EMPTY_TABLE = {};
/**
* The table, resized as necessary. Length MUST Always be a power of two.
* 这个是HashMap底层用来存储的数组
*/
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
/**
* 这个是HashMap中的一个内部类
* 这是一个单链表
* key/value放入HashMap的时候都会被包装成Entry<K,V>对象
*/
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
//这个 next是和Entry<K,V>本身类型一样,是一个单链表
Entry<K,V> next;
int hash;//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;
}
2.HashMap包含了一个Entry(key,value,next,hash)的内部类, key/value放入HashMap的时候都会被包装成Entry的对象
/**
* 这个是HashMap中的一个内部类
* 这是一个单链表
* key/value放入HashMap的时候都会被包装成Entry<K,V>对象
*/
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
//这个 next是和Entry<K,V>本身类型一样,是一个单链表
Entry<K,V> next;
int hash;//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) {
}
}
/**
* Adds a new entry with the specified key, value and hash code to
* the specified bucket. It is the responsibility of this
* method to resize the table if appropriate.
*
* Subclass overrides this to alter the behavior of put method.
*/
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);
}
/**
* Like addEntry except that this version is used when creating entries
* as part of Map construction or "pseudo-construction" (cloning,
* deserialization). This version needn't worry about resizing the table.
*
* Subclass overrides this to alter the behavior of HashMap(Map),
* clone, and readObject.
*/
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++;
}
3.HashMap的成员就有Entry的数组,该数组的大小默认就是16,大小永远是2的次方数,如果自己给出的大小不是2的次方数会转换成大于并最接近自己给出的2的次方数
/**
* The default initial capacity - MUST be a power of two.
* 默认的大小是左移4位相当于16(2的4次方)
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 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;
4.put(key,value)时其实就是转换成Entry对象并放入数组中
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;
}
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++;
}
5.put方法的实现
第一步:根据key的hashCode进行hash运算(hash算法不用关心),得到hash
第二步:根据hash值去确定数组的位置
/**
* Returns index for hash code h.
*/
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non zero power of 2";
//等价于 h % (table.length-1) 获取对应的在数组中的位置 当length是2的次方时才成立
return h & (length-1);
}
第三步:(没有发生冲突)如果这个位置没有元素存在,直接包装Entry的实例并给数组元素赋值
(发生从冲突)如果计算出的位置已经有元素存在,就要
遍历整个链表,去判断是否有相同的key,
如果有相同的key则覆盖,如果都没有覆盖的话,则插入到链表的头部。
注意1:如果计算出来的位置相同,这就是冲突率,我们要减少冲突率,因为一旦放入链表中,以后总是要遍历链表,效率差,要尽量把元素直 接放入数组,而非链表,根据实际要求去重写hashcode和equals
注意2:底层是数组,尽量减少扩容,所以HashMap放入元素的时候应该估算数组的大小,避免扩容操作,()。
HashMap并不是全部放满数据后再扩容,它有一个加载因子默认是0.75,即默认的是16*0.75=12 时进行扩容
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
//默认扩容2倍
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
所以理论上,hashCode可能存在冲突的情况,有个专业名词叫
碰撞
,当碰撞发生时,计算出的
bucketIndex
也是相同的,这时会取到
bucketIndex
位置已存储的元素,最终通过equals来比较,equals方法就是哈希码碰撞时才会执行的方法,所以前面说HashMap很少会用到equals。HashMap通过hashCode和equals最终判断出K是否已存在,如果已存在,则使用新V值替换旧V值,并返回旧V值,如果不存在 ,则存放新的键值对<K, V>到
bucketIndex
位置。文字描述有些乱,通过下面的流程图来梳理一下整个put过程。
第四步:如何通过key获取value(get方法的实现)
通过key查找元素的算法和放入是一样的。
所以一旦key放入HashMap就不应该修改,和Hashcode和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;
}