hashmap的get和put操做的时间复杂度是常量。经过调用哈希函数将元素正确的分布到桶中。初始容量(capacity)的值不能设置过高,加载因子(loadfactor)不能设置的过低,不然会影响迭代的性能。
一个hashmap的实例有两个参数将影响它的性能。初始容量、加载因子。初始容量是hashmap在建立时候桶的大小。加载因子用来肯定什么时候进行扩容(size > 容量*加载因子)。扩容的时候也会进行对内部的数据结构进行从新构建,使桶的大小增长两倍。java
默认的加载因子(0.75)在时间和空间复杂度上提供了很好的权衡。大一点的话会减小空间可是会增长get和put的时间。node
hashmap能够存键值为null,是线程不安全的。若是想线程安全可使用Collections.synchronizedMap()包装.
或者使用ConcurrentMap,这个map是线程安全的。数组
hashmap是一个散列表,存储的内容是key-value。就像咱们用的字典同样,用过字母(key)查找单词(value)。hashmap的时间复杂度是O(longN)。安全
在java8以前hashmap采用的是桶+链表的数据结构。可是若是数据很大,链表的查找时间复杂度是O(n),显然者违背了hashmap的初衷,因此在链表的元素大于8的时候,java8会把链表旋转为红黑树。微信
[数组 链表 散列(hash)
](https://blog.csdn.net/u013565...数据结构
桶的实现:app
transient Node<K,V>[] table;
链表的实现:函数
static class Node<K,V> implements Map.Entry<K,V> { final int hash;//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; } //方法是线程不安全的 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; } 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 int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默认的桶初始容量(2^4=16)。 static final int MAXIMUM_CAPACITY = 1 << 30;//最大的桶的容量 static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认的加载因子 static final int TREEIFY_THRESHOLD = 8;//当链表大于这个阈值会被旋转为红黑树 static final int UNTREEIFY_THRESHOLD = 6;//当作resize操做的时候,若是桶中某个节点的数量小于这个阈值,则把树旋转为链表 static final int MIN_TREEIFY_CAPACITY = 64;//当桶中的数量大于64是,才会判断是否转换成树 transient Node<K,V>[] table;//桶 transient int size;//hashmap的存储的元素大小 transient int modCount;//hashmap结构被修改的次数 int threshold;//扩容阈值 final float loadFactor;//加载因子
构造方法会建立一个空的桶,计算扩容阈值和加载因子源码分析
public HashMap(int initialCapacity, float loadFactor) {//桶初始化容量,加载因子 if (initialCapacity < 0)//桶初始容量不能小于0 throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY)//若是桶初始化容量大于hashmap最大的容量,则初始化容量等于最大的容量 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);//加载因子为默认的0.75 }
public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; //桶初始容量为0,加载由于0.75 }
public HashMap(Map<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR;//加载因子为默认的0.75 putMapEntries(m, false);//map放入桶中 } final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) { int s = m.size();//插入元素大小 if (s > 0) {//若是大于0 ,则继续进行插入操做 if (table == null) { // pre-size 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(); 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);//插入元素 } } }
public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } //计算hash static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } //根据key获取value final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k;//tab:桶 first:桶中节点的第一个元素 n:桶的长度 k:第一个节点的key if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {//若是桶不为空,而且key所在的节点的第一个元素不为空 if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k))))//若是key是节点的第一元素则返回节点的第一个元素 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; }
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; 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);//若是key所在的桶第一个元素为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)//若是hashmap中的元素等于扩容阈值,则从新构造数据结构 resize(); afterNodeInsertion(evict); return null; }
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
h是原始的hash返回的值是int类型,int取值范围:-2147483648到2147483648,先后加起来大概四十亿的映射空间。只要hash函数映射的比较松散,通常是很难出现碰撞的。
可是考虑到实际的内存的大小,很难放下这么大的数组。性能
因此为了空间上的考虑上述中的扰动函数,对原始计算出来的hash值(int 四个字节32位),右移16位,本身的高半区和低半区作异或,就是为了混合原始hash值的高位和地位,以此来加大低位的随机性。并且混合后的地位参杂了高位的部分特征,这样高位的信息也被变相的保留下来了。
hashmap线程不安全的,若是要使用安全的hashmap建议使用ConcurrentHashMap。
参考:
hash()原理: https://www.zhihu.com/questio...
关注个人公众号第一时间阅读有趣的技术故事
扫码关注:也能够在微信搜索公众号便可关注我:codexiulian 渴望与你一块儿成长进步!