TreeMap
TreeMap的底层是通过红黑树来实现的。
一、源码
Entry节点
每一个树节点保存着键值对Entry<K, V>
static final class Entry<K,V> implements Map.Entry<K,V> {
K key;
V value;
Entry<K,V> left; // 左子节点
Entry<K,V> right; // 右子节点
Entry<K,V> parent; // 父节点
boolean color = BLACK; // 节点的颜色,有BLACK和RED
Entry(K key, V value, Entry<K,V> parent) { // Entry构造函数
this.key = key;
this.value = value;
this.parent = parent;
}
...
}
添加put
由于TreeMap是通过红黑树实现的,因此可以先参考博客,里面详细讲解了红黑树,会使得对put操作的理解更清晰。
首先需要找到给定的key、value要插入的位置,如果树中已经存在,用value覆盖原来的值;
然后,插入新节点之后需要调整红黑树,使之平衡。
public V put(K key, V value) {
Entry<K,V> t = root;
// 判断树的根节点是否为空
// 如果为空,表示这是第一次添加。那么用key,value创建一个新的节点,并设置为根节点
// 反之,不为空,表示已经有根节点了
if (t == null) {
// 检查key是否为空
compare(key, key);
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// 获取比较器
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {
parent = t; // 设置parent为t,初始值为root
cmp = cpr.compare(key, t.key); // 比较当前要插入的key与t节点的key的大小
if (cmp < 0) // 如果新值小,则向左子树走
t = t.left;
else if (cmp > 0) // 新值大,向右子树走
t = t.right;
else // 相等 则树中存在该key,那么更新值为value,并返回旧值
return t.setValue(value);
} while (t != null);
// 循环,要么找到相等的key;要么找到null,表示在这个位置上添加节点
}
// else的逻辑与上面相似
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
// 使用key,value创建一个新的节点,且其父节点为parent
Entry<K,V> e = new Entry<>(key, value, parent);
// 上面的比较器最后的值cmp可以知道是左儿子 或右儿子
if (cmp < 0)
parent.left = e;
else
parent.right = e;
// 平衡红黑树
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
private void fixAfterInsertion(Entry<K,V> x) {
// 新插入节点置为红色
x.color = RED;
// 重点:节点的父节点为红色时,才需要分情况讨论
while (x != null && x != root && x.parent.color == RED) {
// 如果父节点是祖父节点的左儿子
if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
// y为x的叔叔节点
Entry<K,V> y = rightOf(parentOf(parentOf(x)));
// 如果叔叔节点y为红色
if (colorOf(y) == RED) {
setColor(parentOf(x), BLACK);
setColor(y, BLACK);
setColor(parentOf(parentOf(x)), RED);
x = parentOf(parentOf(x));
}
// 叔叔节点y不存在或为黑色
else {
// 如果x是父节点的右儿子,先左旋、再右旋
// 如果x是父节点的左儿子,只用左旋
if (x == rightOf(parentOf(x))) {
x = parentOf(x);
// 将父节点左旋
rotateLeft(x);
}
setColor(parentOf(x), BLACK);
setColor(parentOf(parentOf(x)), RED);
// 左旋
rotateRight(parentOf(parentOf(x)));
}
} else {
Entry<K,V> y = leftOf(parentOf(parentOf(x)));
// 如果叔叔节点为红色
if (colorOf(y) == RED) {
setColor(parentOf(x), BLACK);
setColor(y, BLACK);
setColor(parentOf(parentOf(x)), RED);
x = parentOf(parentOf(x));
}
// 如果叔叔节点不存在或为黑色
else {
// 如果x是父节点的左儿子,先右旋、再左旋
// 如果x是父节点的右儿子,只用左旋
if (x == leftOf(parentOf(x))) {
x = parentOf(x);
rotateRight(x);
}
setColor(parentOf(x), BLACK);
setColor(parentOf(parentOf(x)), RED);
rotateLeft(parentOf(parentOf(x)));
}
}
}
// 根节点为黑色
root.color = BLACK;
}
HashMap
HashMap采用哈希表存储方式,哈希表的主干为数组。通过将元素按照某个函数映射到数组中的位置,完成查找、添加、删除操作。即存储位置 = hash(元素),hash为哈希函数。
不可避免地会出现不同的元素的 hash 值相等的情况,这被称作哈希冲突(哈希碰撞)。解决哈希冲突的方法有:开放定址法、再散列函数法、链地址法。我们常用的HashMap
使用的就是链地址法,即以数组为主体,存储Entry
键值对,当遇见冲突时,该键值对生成一个链表,链表存储所有具有相同hashCode
值的键值对元素。也就是说,HashMap
采用数组+链表的形式。
1.7以前HashMap采用数组+链表形式存储
哈希函数计算元素在数组中存放的位置下标为 i i i:
如果 i i i为空,直接插入;否则将其转换为一个链表,再插入;如果 i i i位置已经存储的是链表的结构,那么在链表中寻找 k e y key key,找到,直接覆盖 v a l u e value value,没有找到,则链表尾插新节点 ( k e y , v a l u e ) (key, value) (key,value)1.8之后HashMap采用数组+链表+红黑树形式存储
由于1.7里面链表的存储结构会造成 O ( m ) O(m) O(m)的时间复杂度,即 i i i位置存放了 m m m个节点,那么需要遍历所有 m m m个节点。非常的耗时,浪费资源。因此在1.8中引入
红黑树
来提升HashMap的性能。
当链表的长度>=8时,将链表转化为红黑树,这样查询的效率变为 O ( l o g 2 m ) O(log_2m) O(log2m),大大提升了性能
一、常用方法
方法 | 含义 |
---|---|
.put(Object key, Object value) | 添加一个键值对;如果存在键key,修改value值 |
.size() | 存在的键值对个数 |
.containsKey(Object key) | 是否存在键key |
.containsValue(Object value) | 是否存在值value |
.get(Object key) | 获取键为key对应的value |
.remove(Object key) | 删除键为key的键值对 |
遍历HashMap
-
使用Entry集遍历
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) { System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue()); }
-
对keySet遍历
for(String key :hashMap.keySet()) { System.out.println("key = " + key + ", value = " + hashMap.get(key)); }
-
对values遍历
该方法不能得到key
for(Integer value : hashMap.values()) { System.out.println("value = " + value); }
-
使用Iterator迭代器遍历
将hashMap转为Set集合,并使用set的迭代器来遍历
HashMap<String, Integer> hashMap = new HashMap(); hashMap.put("g", 123); hashMap.put("o", 345); hashMap.put("d", 789); Iterator iterator = hashMap.entrySet().iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } /* 输出: d=789 g=123 o=345 */ while (iterator.hasNext()) { Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) iterator.next(); System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue()); } /* 输出: key = d, value = 789 key = g, value = 123 key = o, value = 345 */
个人认为第一种和第二种用的比较多。
二、1.8 HashMap源码
以下是从1.8的源码来学习HashMap以及其相关操作。
默认参数
// 默认初始容量 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 最大容量 10^30 十几亿,基本不会达到
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认 负载因子 0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 转化为红黑树的节点数阈值
static final int TREEIFY_THRESHOLD = 8;
// 去红黑树的节点数阈值
static final int UNTREEIFY_THRESHOLD = 6;
// 最小红黑树的容量 链表转红黑树的数组长度的临界值
static final int MIN_TREEIFY_CAPACITY = 64;
// HashMap中的数组结构
transient Node<K,V>[] table;
// 键值对的数量
transient int size;
// 扩容的临界值
int threshold;
// 负载因子
final float loadFactor;
CAPACITY
指容量,默认为16。一般扩充为原来的2倍,即容量为
2
n
2^n
2n。
LOAD_FACTOR
指负载因子,默认为0.75。即容量达到75%时(表示快满了),就为HashMap扩容,扩充2倍的容量。并将数据复制到新的数组中,原来的数组变为垃圾。
HashMap的性能一般与CAPACITY
和LOAD_FACTOR
有关。
- 初始
CAPACITY
低,节约空间,但是增加hash的频率,开销大;初始CAPACITY
高,减少重新hash频率,但增加初始的内存消耗,增加迭代的次数 (因此,高初始容量一般用于大量元素且迭代次数少的情况,低初始容量用于少元素且多迭代的情况) LOAD_FACTOR
小,增加内存消耗,不断的扩容;LOAD_FACTOR
大,降低性能,很难进行扩容
threshold
阈值,一般是capacity * loadFactory
数组下标位置
,即键值对在数组中的位置下标:
index = hash % length
可以用 index = hash & (length - 1) 来计算,即hash与length-1二进制进行与运算
节点属性
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; // 节点key的hash值
final K key; // key
V value; // value
Node<K,V> next; // 链表,结点的下一个节点
// Node构造函数
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
}
添加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;
// 数组为空时
if ((tab = table) == null || (n = tab.length) == 0)
// 对数组扩容
n = (tab = resize()).length;
// 如果数组中i位置为空,且p = tab[i]上的节点
if ((p = tab[i = (n - 1) & hash]) == null)
// 向数组该位置添加元素
tab[i] = newNode(hash, key, value, null);
// 如果i位置已经有元素
else {
Node<K,V> e; K k;
// 判断p即第一个位置上的数据和我们给定的数据是否一样,一样的话,取出该节点e
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 如果p是红黑树节点,调用红黑树插值方法
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 如果p是链表节点
else {
// 遍历链表
for (int binCount = 0; ; ++binCount) {
// 链表中不存在该数据,新建节点并加入到链表后面
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 如果链表长度超出转红黑树的阈值 8
if (binCount >= TREEIFY_THRESHOLD - 1)
// 转化为红黑树
treeifyBin(tab, hash);
break;
}
// 链表中存在该数据,取出e
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 给定的键值对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;
}
计算hash值
// 计算哈希值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
为什么要向右移16位?
如果没有右移,则h的末位可能都是0。
比如两个h的最后4位都是0(这个的概率还是蛮大的)。在后面计算数组下标位置 i 时,hash & (length - 1),由于length-1 = 15(1111),那么这两个key对应的 i 都是0,导致碰撞冲突,散列不均匀。
因此,右移16位可以减小冲突,使得散列更均匀
数组扩容
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; // double threshold
}
// 对应使用 new HashMap(int initialCapacity) 初始化后,第一次put操作
else if (oldThr > 0)
newCap = oldThr;
// 对应使用 new HashMap() 初始化后,第一次 put 的时候
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"})
// 新建一个长度为newCap的数组
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;
// 注意是 hash & oldCap,而不是 hash & (oldCap - 1)
// 即元素在数组中的位置是否需要移动
// 不需要移动
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;
}
为什么扩容的长度一定要是 2 n 2^n 2n?
- 长度为 2 n 2^n 2n可以保证新数组和原数组的索引一致
- 使数组能够充分散列
- 长度为 2 n 2^n 2n可以使得 h a s h % l e n g t h = h a s h & ( l e n g t h − 1 ) hash \% length = hash \& (length - 1) hash%length=hash&(length−1),提升计算效率(&指二进制的位运算)
比如,length=16(10000),则length-1=15(1111)。那么对于每一个HashCode都可以对应唯一的索引值,充分散列。
在扩容时,保证元素的索引位置不变。比如hashCode为(0 1 0 0 1)的元素,在长度为16的数组中的下标应为(0 1 0 0 1)&(0 1 1 1 1) = (0 1 0 0 1).当进行扩容后,数组长度为32,则对应的下标位置为(0 0 1 0 0 1)&(0 1 1 1 1 1)=(0 0 1 0 0 1),下标索引一致。
因此,使用 2 n 2^n 2n长度可以减少哈希碰撞,让元素均匀添加到数组中(充分的散列),且尽最大可能的避免掉链表的出现。
三、1.8 HashMap添加put总结
四、HashMap与HashTable的区别
- HashMap线程不安全,HashTable线程安全
- HashMap效率高,HashTable效率不高
- HashMap可以有一个Key为null,而HashTable不允许键为null
- 扩容规则不一样。HashMap长度必须为 2 n 2^n 2n,且扩容为原来的两倍;HashTable扩容为 2 n + 1 2n+1 2n+1