关于HashMap经验分享(源码分析)

时间:2022-05-04 19:24:35

集合的作用就是以一定的方式组织,存储数据。对于HashMap,我认为需要的关注以下内容:
 1.集合的基本存储单元
 2.集合的增删改查基本操作的实现
 3.存储数据的要求,是否为空,是否允许重复
 4.存放与读取是否有序
 5.是否线程安全

首先,我在这里介绍下集合的家庭族谱。总的来说,java中所用的集合,都是实现了Collection接口的,类继承图如下:

Collection<--List<--Vector Collection<--List<--ArrayList Collection<--List<--LinkedList Collection<--Set<--HashSet Collection<--Set<--HashSet<--LinkedHashSet Collection<--Set<--SortedSet<--TreeSet 关于HashMap经验分享(源码分析)

基本存储单元

 HashMap的源码片段:

/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;

/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
*/
transient Set<Map.Entry<K,V>> entrySet;

/**
* The number of key-value mappings contained in this map.
*/
transient int size;

/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
transient int modCount;

/**
* The next size value at which to resize (capacity * load factor).
*
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
int threshold;

/**
* The load factor for the hash table.
*
* @serial
*/
final float loadFactor;
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
}

基于Node数组和Node链表的实现。

集合的增删改查基本操作的实现

1.新增元素

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

先用hash算法取出Node数组下标index;如果当前数组下标为index的Node不存在数据,即无hash冲突,新建Node直接放入此数组中,当然,这个Node的next为null。接下来讨论hash值冲突的情况:1.hash值冲突而且key值相同,此时将此Node的value用新的值覆盖;2.hash值冲突但key值不同,此时需要新建一个Node,并将上一个Node的next指向当前新建的newNode,作为链表实现。

static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

Hash算法。

2.修改元素

同put方法,直接覆盖value值。


3.删除元素

 
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}

通过key计算出hash,通过hash计算中数组index下标。取出数组index里的第一个元素,如果key与第一个元素的key相同,而且此index不存在hash冲突,直接将此元素置为null;如果存在hash冲突,将这个数组的第一个元素设置为当前Node的next指向的Node。

4.寻址

final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}

取出数组下标位置很重要,根据hash值计算。

存储数据的要求,是否为空,是否允许重复

允许为空或者null,当key值为空或null时,hash值默认0,计算出的数组下标为0,也就是说key值为null或者空串的,永远在第一个位置,并用链表链接,key值不允许重复,value值允许重复,hash值允许重复。

存放与读取是否有序

底层实现基于hash算法,无序。

是否线程安全

非线程安全,因为所有方法都是不同步的,而且都是final,方法不能修改。