Collection探究之HashMap
来源:互联网 发布:淘宝阿里旺旺在哪里 编辑:程序博客网 时间:2024/05/22 03:50
在讲hash map之前先简单的讲讲hashcode。hash意思为散列,它能将任意长度的输入,通过散列算法的计算,输出固定长度,该输出就为散列值(hashcode)。
为什么会需要hashcode呢?可以想象我们需要将不同的元素存放入集合,为了快速查找与区分它们,可以使用hash算法将各个元素映射成为固定长度的hashcode,如:王--1、而--2、你--3……这样,根据不同的hashcode将元素存到该数组下标为hashcode值的位置,在需要查找该元素时,只需将元素进行hash算法,得到hashcode之后,用该hashcode作为下标去数组中取元素就可以了。
接下来说说HashMap,它不是继承自Collection容器,它是基于Map接口实现的。在Map中存放的是key—value数据,key是通过hash算法后形成的hashcode,value为我们需要存放的数据,通过key能找到我们所需的value。但是hash算法也不是万能的,因为在数据量非常大的时候,很有可能两个不同的key在通过hash算法时会产生相同的hashcode,这就是hash冲突,为了解决这个问题,HashMap底层基于数组与链表来实现,下面是我从网上找的图:
数组的每一个元素为一个链表,若hashcode相同,则将数据依次存入链表中。下面,我们来看一下HashMap的源码。
1. HashMap的定义
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
可以看到HashMap是继承自AbstractMap的,它实现了Map、Cloneable、Serializable接口。
2. HashMap的属性
//table为存放key的数组,可以看到节点类型为Node transient Node<K,V>[] table; //定义变量entrySet,类型为一个Set,代表着一个Map实体(key-value对)。 transient Set<Map.Entry<K,V>> entrySet; //HashMap的容量 transient int size; //操作数 transient int modCount; //容量的临界值,当实际容器的容量大于(总容量*扩容比率)时进行扩容 int threshold; //扩容比率 final float loadFactor; //默认的HashMap的初始容量,大小为16。 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //HashMap的最大容量,2的30次方 static final int MAXIMUM_CAPACITY = 1 << 30; //这是一个默认的数据容量阈值因子,也就是说,若HashMap中数据数量超过HashMap容量的3/4时,HashMap就会扩容 static final float DEFAULT_LOAD_FACTOR = 0.75f; //这也是一个阈值,在HashMap的每个数组上的链表的元素数量超过8个时,该链表会变为红黑树,为了提升查找效率。 static final int TREEIFY_THRESHOLD = 8; //有时候链表中的数据会删除,当链表中数据数量小于6时,该链表会不使用红黑树。 static final int UNTREEIFY_THRESHOLD = 6; static final int MIN_TREEIFY_CAPACITY = 64; //Node为HashMap中链表的节点,用于存放数据。 static class Node<K,V> implements Map.Entry<K,V> { //hashcode final int hash; final K key; V value; //指向链表的下一个节点。 Node<K,V> next; Node(int hash, K key, V value, Node<K,V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; }
3.HashMap的构造函数
//设定初始化容量和扩容比率 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; //tableSizeFor为新的扩容方法 this.threshold = tableSizeFor(initialCapacity); }//用于确定每次HashMap扩容容量总是2的n次方,为是2的n次方呢?在后面会详细说static final int tableSizeFor(int cap) { int n = cap - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; } //调用默认的扩容比率进行初始化HashMap容器 public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; } //使用Map类型的对象来初始化HashMap容器,将m中的key-value元素都加载入HashMap public HashMap(Map<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); }final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) { //传入Map的容器大小,实际容器大小 int s = m.size(); if (s > 0) { //table表示hash表,也就是key数组 if (table == null) { //初始化数组大小 float ft = ((float)s / loadFactor) + 1.0F; //边界检查,是否超出容器的最大容量 int t = ((ft < (float)MAXIMUM_CAPACITY) ? (int)ft : MAXIMUM_CAPACITY); //若当前容器大小超出了容器的临界值,则更新临界值 if (t > threshold) threshold = tableSizeFor(t); } // 若实际容量大小超过临界值,则进行扩容 else if (s > threshold) //扩容函数 resize(); //将m中的元素复制到HashMap中 for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) { K key = e.getKey(); V value = e.getValue(); putVal(hash(key), key, value, false, evict); } } }//扩容函数final Node<K,V>[] resize() { //获取原HashMap的Hash表 Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) { //若超过了2的30次方则无法再若容,只能改变容器的临界值的大小 if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } //扩容后的新容量为老容量的2倍 else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) //容器的临界值也变为原来的两倍 newThr = oldThr << 1; } //若oldCap<0,oldThr > 0那么新容量大小等于容量临界值大小 else if (oldThr > 0) newCap = oldThr; 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"}) //初始化新的hash表 Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab; if (oldTab != null) { //将m数组复制到新的数组中,这里分两种情况1.红黑树 2链表 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; }
4.HashMap的一般操作
4.1 添加key-value
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }//该方法用于将key-value放入HashMap中final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { //初始化hash表和节点 Node<K,V>[] tab; Node<K,V> p; int n, i; //若表为空或者表的长度为0 if ((tab = table) == null || (n = tab.length) == 0) //进行新建hash表,并得到表的容量 n = (tab = resize()).length; //若在表中n-1的位置为空,直接将数据存放进去 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; //若存在数据,且需要插入的数据与已经存在数据的key相同,则进行value覆盖 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) { //查找链表的末尾节点,找到则在尾部插入新插入的key-value if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); //若已经处理的链表节点值到8个,则将链表转换成为红黑树 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } //更新p的下一个指针 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; }
4.2移除某个key的元素
//调用removeNode来实现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; //获取根据hash与key查找到的节点p,若只有链表上只有一个节点 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 { //匹配节点的hash值与key 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; }
先说一下为什么每次都是2的N次方,因为在上面的操作我们可以看到在定位值时(n - 1) & hash操作,n为当前hashMap的容量,当n为2的N次方时,(n - 1) & hash等效于hash%n,所以效率非常高,因为2
的N次方必定只有N位为1其余都为0,而当n -1时,N位为0,其后都为1,所以在运算时能够增加效率。
4.3获取元素
//交给getNode获取元素值 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找到key的链表头 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; }
具体的代码分析就到此为止了,由于1.8的HashMap代码改动较大,不知本人的理解是否有误,若有错误,希望大家可以指出。
- Collection探究之HashMap
- Collection探究之ArrayList
- Collection探究之LinkedList
- Collection探究之Vector
- Collection探究之HashSet
- java collection之 HashMap
- 深入Collection之HashMap
- java基础之HashMap细节探究
- HashMap详细探究
- HashMap和Hashtable探究
- HashMap源码探究
- 探究HashMap数据结构
- HashMap-Java8 HashMap实现原理探究
- HashMap 死循环的探究
- HashMap 死循环的探究
- HashMap 死循环的探究
- java HashMap 实现原理探究
- 探究HashMap的实现原理
- 如何限制对象只能建立在堆上或者栈上
- 谷歌面试题 多线程的同步与互斥操作
- linux下svn客户端安装及使用
- cygwin自动安装工具
- catalan数 + 二叉树 —— POJ 1095
- Collection探究之HashMap
- 【LeetCode从零单刷】Set Matrix Zeroes
- 设计模式之--依赖倒置原则
- iOS 中利用 Masonry 进行代码适配的基本方法
- sqlite3的安装和使用
- ACCESS注入
- 终章-剑之魂
- CodeVS4419FFF团的菊花
- Markdown 指引 留作备份