
hashMap概览
- hashmap的数据结构包括了初始数组,链表,红黑树
- 插入数据的时候使用pos=key%size来进行插入数据
- 当两个或者以上的key的key相同且key值不同的时候(发生冲突),就会挂在数组初始位置的链表后
- 当某个节点后出现过多的链表节点的时候,就会转换成红黑树以提高效率
hashmap的数据结构包括了初始数组、链表、红黑树
public HashMap() {this.loadFactor = DEFAULT_LOAD_FACTOR; }
put方法
public V put(K key, V value) {return putVal(hash(key), key, value, false, true);}
static final int hash(Object key) {int h;return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);}
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { LinkedHashMap.Entry<K,V> first;if (evict && (first = head) != null && removeEldestEntry(first)) {K key = first.key;removeNode(hash(key), key, null, false, true);}
}
hash冲突解决
static final int hash(Object key) {int h;return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);}
扩容
else if (s > threshold);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; }else if (oldThr > 0) newCap = oldThr;else { 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 { Node<K,V> loHead = null, loTail = null;Node<K,V> hiHead = null, hiTail = null;Node<K,V> next;do {next = e.next;if ((e.hash & oldCap) == 0) {if (loTail == null)loHead = e;elseloTail.next = e;loTail = e;}else {if (hiTail == null)hiHead = e;elsehiTail.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;}
get方法
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 && ((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;}
remove方法
map序列化
private void writeObject(java.io.ObjectOutputStream s)throws IOException {int buckets = capacity();s.defaultWriteObject();s.writeInt(buckets);s.writeInt(size); internalWriteEntries(s);}
反序列化
private void readObject(java.io.ObjectInputStream s)throws IOException, ClassNotFoundException {s.defaultReadObject();reinitialize();if (loadFactor <= 0 || Float.isNaN(loadFactor))throw new InvalidObjectException("Illegal load factor: " +loadFactor);s.readInt(); int mappings = s.readInt(); if (mappings < 0)throw new InvalidObjectException("Illegal mappings count: " +mappings);else if (mappings > 0) { float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f);float fc = (float)mappings / lf + 1.0f;int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ?DEFAULT_INITIAL_CAPACITY :(fc >= MAXIMUM_CAPACITY) ?MAXIMUM_CAPACITY :tableSizeFor((int)fc));float ft = (float)cap * lf;threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ?(int)ft : Integer.MAX_VALUE);SharedSecrets.getJavaOISAccess().checkArray(s, Map.Entry[].class, cap);@SuppressWarnings({"rawtypes","unchecked"})Node<K,V>[] tab = (Node<K,V>[])new Node[cap];table = tab;for (int i = 0; i < mappings; i++) {@SuppressWarnings("unchecked")K key = (K) s.readObject();@SuppressWarnings("unchecked")V value = (V) s.readObject();putVal(hash(key), key, value, false, false); }}}
总结:
- hashmap的数据结构包括了初始数组,链表,红黑树
- 数组容量是2的倍数:提高运算速度,增加散列度,降低冲突,减少内存碎片
- hash函数与pos定位:hashcode的高16位与低16位进行异或求模,增加了散列度降低了冲突
- 插入冲突:通过单链表解决冲突,如果链表长度超过(TREEIFY_THRESHOLD=8),进行单链表和红黑树的转换以提高查询速度
- 扩容:扩容的条件:实际节点数大于等于容量的四分之三;扩容后数据排布:要么是原下标的位置;要么是原下标+原容量的位置
- 序列化:只存储了数组的容量、实际节点数量和各个节点的key、value值