Hashmap的基本性质
1、Hashmap是通过计算元素的hashcode来散列存储元素的一种数据结构。Hashmap内部数据结果是数组+链表+红黑树的组合,其中数组在其内部称为桶(bucket),每一个桶都是链表或者红黑树(在特定条件下会相互转化)。Hashmap特点是可以快算的存储和获取其中元素。理想的状态下所有元素可以散列分布到所有桶中。
2、在第一点提到理想状态下是Hashmap中的每个元素都是散列分布到所有的桶中,即数组中的每个桶都只是保存一个元素,也就是说数组中每个元素的链表都是只有一个数据,其实也就是不存在hash冲突的情况了。这个在数据量少的情况下应该是可以实现的,但是在数据量大的情况下,hash冲突貌似是不可避免的情况,这时候的问题就是要解决hash冲突了。Hashmap解决hash冲突的办法是拉链法(还有其他解决hash冲突的方法,以后再学习总结),这个就是Hashmap每个桶中以链表+红黑树存储的原因了。
3、Hashmap中可以存储key和value都是null的元素,但是key=null的元素只能有一个。Hashmap不是线程安全的,其中数组的大必须是2的n次方,默认初始的数组大小是16,负载因子是0.75,所以在元素占用了16*0.75=12个桶的时候,hashmap会进行扩容。
/**
* 默认数组初始大小
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 默认的负载因子
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
Hashmap的源码学习
1、数组(桶)
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;
Node是其中的内部类,Hashmap就使用Node数组来作为元素的存储。
2、链表+红黑树
在Java8中hashmap引入了红黑树来解决hash冲突,主要是由于性能优化的问题。在Hashmap中put/get操作都是需要找到对应的元素,这样都会对链表或者红黑树进行遍历。在时间复杂度方面,链表是O(n),而红黑树是O(logn),这样对比起来,如果在数据量大的情况下,红黑树的查找效率会比链表高很多,当然Hashmap也会提升很大的性能了。
put操作:如果有hash冲突,返回的是旧值
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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);
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)
resize();
afterNodeInsertion(evict);
return null;
}
get操作
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @see #put(Object, Object)
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
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;
}
3、在链表和红黑树的转换中,有两个关键的阈值,一个是链表转红黑树的阈值8,一个是红黑树转链表的阈值6,这些阈值的设置应该是涉及到离散数学的理论,就不深究了。在源码的注释中,提到的是根据泊松分布,来设置阈值。
为什么会选择红黑树而不是使用二分查找树来替换呢?
这是因为二分查找树如果在最坏的情况下,会变成线性结构的树,这样就相当于退化成链表了。而红黑树本质是平衡二叉树,根据一些它自己的特征,在增加,删除元素的时候,需要进行旋转的操作来保持红黑树的平衡,虽然在保持平衡的过程中会有性能的付出开销,但是对于数据量很大情况下,相对于查询效率来说还是值得的。
TODO:红黑树的一些具体特性(红黑树的定义规则,红黑树节点的性质,左右节点和根节点的数据关系等等),以后再开文学习总结了。
先简单贴下红黑树的定义规则:
- 节点是红色或黑色。
- 根是黑色。
- 所有叶子都是黑色(叶子是NIL节点)。
- 每个红色节点必须有两个黑色的子节点。(从每个叶子到根的所有路径上不能有两个连续的红色节点。)
- 从任一节点到其每个叶子的所有简单路径都包含相同数目的黑色节点。
/**
* 链表转红黑树阈值
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 红黑树转链表阈值
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;