Java集合类-HashMap分析
HashMap的特点
非线程安全
支持序列化
动态扩容
JDK1.6采用数组 + 链表实现,JDK1.8采用数组 + 链表 + 红黑树实现(当链表长度达到8时,再插入新的结点将链表转换为红黑树)
成员变量
常量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默认初始容量16
static final int MAXIMUM_CAPACITY = 1 << 30; // 最大容量2^30
static final float DEFAULT_LOAD_FACTOR = 0.75f; // 默认加载因子
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
属性值
transient Node<K,V>[] table; // 拉链法实现
transient Set<Map.Entry<K,V>> entrySet;
transient int size;
transient int modCount;
int threshold; // 临界值 = 容量 * 加载因子
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; }
拉链法,数组和链表的结合
构造函数
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); this.loadFactor = loadFactor; this.threshold = tableSizeFor(initialCapacity); } public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted }
基本方法
增/改 put
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; // 用(n - 1) & hash 取代取模,效率更高 if ((p = tab[i = (n - 1) & hash]) == null) // table[i]不存在 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)))) // table[i]头结点的key为要存储的key,进行覆盖 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; } final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) { if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } if (newThr == 0) { float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab; if (oldTab != null) { for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) { oldTab[j] = null; if (e.next == null) newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order Node<K,V> loHead = null, loTail = null; Node<K,V> hiHead = null, hiTail = null; Node<K,V> next; do { next = e.next;
// 根据hash & oldCap == 0 将原有的链表分为两段 if ((e.hash & oldCap) == 0) { if (loTail == null) loHead = e; else loTail.next = e; loTail = e; } else { if (hiTail == null) hiHead = e; else hiTail.next = e; hiTail = e; } } while ((e = next) != null); if (loTail != null) { loTail.next = null; newTab[j] = loHead; } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab; }
删 remove
public V remove(Object key) { Node<K,V> e; return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value; } 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; }
1、找到要删除结点在数组中的索引,通过hash、key两个值判断结点位置
2、判断结点是否是头结点或是树节点,如果是头结点将其next置为头结点,如果不是删除该结点。
查 get
public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } 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; }
1、通过hash值找到做属的链表
2、判断是否是链表的头结点、是否是树节点,否则遍历链表找到该结点
取hash值
static final int hash(Object key) { int h;
// 对象的hashcode异或hashcode无符号有移16位 return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
由hash值找到数组索引
(n - 1) & hash
n是2的幂,效果等同于 hash % (n -1),但是效率较高,同样为了达到key值均匀的分布
HashMap扩容原理
初始化
默认初始容量为16, 默认加载因子0.75,临界值=12。
动态扩容
1、将容量扩大为两倍,临界值扩大为两倍
2、将链表根据 hash & oldCap 分为两个链表,两个链表在数组中的位置为原索引位 [j] 和 新位置 [j + oldCap]
相关类和方法
一些问题
参考
http://blog.csdn.net/ns_code/article/details/36034955
http://blog.csdn.net/great_smile/article/details/53119489
逻辑操作符号 与&& 或|| 非!
位操作符号 与& 或| 非~ 异或^