HashMap源代码
2016-03-21 23:01
260 查看
1. 简介
在JDK1.6中,HashMap采用位桶+链表实现,即使用链表处理冲突,同一hash值的链表都存储在一个链表里。但是当位于一个桶中的元素较多,即hash值相等的元素较多时,通过key值依次查找的效率较低。而JDK1.8中,HashMap采用位桶+链表+红黑树实现,当链表长度超过阈值时,将链表转换为红黑树,这样大大减少了查找时间。2. 数据结构
Node//单链表 static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; //hash值 键 值 下个结点 Node(int hash, K key, V value, Node<K,V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } public final K getKey() { return key; } public final V getValue() { return value; } public final String toString() { return key + "=" + value; } public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } //如果key, value都相等表示两个Node相等 public final boolean equals(Object o) { if (o == this) return true; if (o instanceof Map.Entry) { //注意 Map.Entry<?,?> e = (Map.Entry<?,?>)o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true; } return false; } }
红黑树
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> { TreeNode<K,V> parent; // red-black tree links TreeNode<K,V> left; TreeNode<K,V> right; TreeNode<K,V> prev; // needed to unlink next upon deletion boolean red; //结点颜色属性 TreeNode(int hash, K key, V val, Node<K,V> next) { super(hash, key, val, next); } //其他部分未列出 ... }
Node数组
transient Node<K,V>[] table;
当添加一个元素(key-value)时,就首先计算元素key的hash值,以此确定插入数组中的位置,但是可能存在同一hash值的元素已经被放在数组同一位置了,这时就添加到同一hash值的元素的后面,他们在数组的同一位置,但是形成了链表,所以说数组存放的是链表。而当链表长度太长时,链表就转换为红黑树,这样大大提高了查找的效率。
3. 属性
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { private static final long serialVersionUID = 362498820763181265L; static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量 static final float DEFAULT_LOAD_FACTOR = 0.75f;//填充比 //当put一个元素到某个位桶,其链表长度达到8时将链表转换为红黑树 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;//被修改的次数fast-fail机制 int threshold;//临界值 当实际大小(容量*填充比)超过临界值时,会进行扩容 //后面省略...
4. 构造函数
//构造函数1 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);//新的扩容临界值 } //构造函数2 public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } //构造函数3 public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted } //构造函数4用m的元素初始化散列映射 public HashMap(Map<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); }
5. 扩容
//可用来初始化HashMap大小 或重新调整HashMap大小 变为原来2倍大小 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) {//超过1>>30大小,无法扩容只能改变 阈值 threshold = Integer.MAX_VALUE; return oldTab; } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)//新的容量为旧的2倍 最小也是16 newThr = oldThr << 1; // 扩容阈值加倍 } else if (oldThr > 0) newCap = oldThr;//oldCap=0 ,oldThr>0此时newThr=0 else { //oldCap=0,oldThr=0 相当于使用默认填充比和初始容量 初始化 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; 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; }
6. HashMap的get和put方法
注意HashMap中key和value都容许为nullget方法
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; //hash & (length-1)得到对象的保存位 if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { //判 断hash key if (first.hash == hash && // always检查第一个结点 ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { //如果第一个节点是TreeNode,说明采用的是数组+红黑树结构处理冲突 //遍历红黑树,得到节点值 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; }
put方法
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; //如果tab为空或长度为0,则分配内存resize() if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; //(n - 1) & hash找到put位置,如果为空,则直接put if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; //第一节节点hash值同,且key值与插入key相同 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) { //p第一次指向表头,以后依次后移 if ((e = p.next) == null) { //e为空,表示已到表尾也没有找到key值相同节点,则新建节点 p.next = newNode(hash, key, value, null); //新增节点后如果节点个数到达阈值,则将链表转换为红黑树 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } //容许null==null if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k)))) break; p = e;//更新p指向下一个节点 } } //更新hash值和key值均相同的节点Value值 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; }
相关文章推荐
- 爬虫练习
- python部分高级技巧
- Spring JDBC 随笔
- Springmvc中的return modelAndView和return "xxxx"的区别
- c++ 头文件包含问题-include&class
- 刷题记之代码能力大作战一
- Python 标准库 urllib2 的使用细节
- Java内存之本地内存分析神器: NMT 和 pmap
- python3.5文档
- JAVA中修饰符protected
- java语言程序设计第十版(Introduce to java 10th) 课后习题 chapter6-32
- java 反斜杠转义
- QT学习笔记(1)—字符编码
- PHP中的数据类型转换和类型检测
- 接口与多态的使用
- Java面向对象06-多态,内部类
- Matlab 未找到支持的编译器或 SDK 解决方法归纳
- python 内置函数
- Qt信号槽函数用lambada表达式作为槽函数的陷阱
- 简明Python教程学习笔记_3_模块