源码版本:JDK8
Map是什么?
Map
是Java最常用的接口之一,以键值对的形式保存数据,键不允重复,一个键对应一个值。 至于键、值能不能为空,则看具体的实现。 几个重要实现:HashMap
HashTable
TreeMap
HashMap
HashMap是什么?
HashMap
是Map
接口基于哈希表的实现,该实现实现了Map
接口的所有操作,具有以下特点:
- 键、值允许为空。
- 不保证遍历顺序,跟元素的插入顺序和访问顺序无关
- 线程不同步
- 除非是迭代器
iterator
本身的remove()
方法,否则不允许在遍历的过程删除元素remove(Object key)
。 - 为基本操作( get和put )提供恒定时间性能。
- 因为不管存还是取都是通过hash函数直接计算出位置,所以说其时间性能是恒定的。
类图:
AbstractMap
:提供 Map 接口的骨架实现,以最大限度地减少实现此接口所需的工作量。
HashMap的具体实现?
- 底层使用散列表+红黑树实现(数组+链表+红黑树,数组中放的是链表或红黑树的首节点)
- 键经过hash函数计算,得到在数组中的位置,如果数组该位置不存在元素,则直接放入;如果数组中已存在元素(hash冲突),则放入对应的链表或红黑树中。
- 数组中每一个节点,称为一个“桶”,桶中存放链表的首节点,当桶中的数据过多时(大于
TREEIFY_THRESHOLD
并且数组容量大于MIN_TREEIFY_CAPACITY
),链表结构转换为红黑树结构(红黑树也是链表结构),当桶中的数据量减少时(小于UNTREEIFY_THRESHOLD
),又会从红黑树结构转换回链表结构。 - 当数组的容量达到阈值时(容量*负载因子),会对数组进行扩容。扩容会重新计算所有元素映射位置,是一件很耗费性能的事。所以,初始容量和负载因子的设置对性能会有一定的影响。默认的初始容量16和负载因子0.75是经过大量计算,兼顾性能与速度结果。
- 数组容量小时,遍历速度提高,但hash冲突的几率也会提高。扩容又是一件耗费性能的事。
- 数组容量过大时,hash冲突的几率降低了,但遍历的速度又会受到影响。
几个重要属性
DEFAULT_INITIAL_CAPACITY = 1 << 4
:初始容量16。容量必须是2的冥。DEFAULT_LOAD_FACTOR = 0.75f
:默认的负载因子TREEIFY_THRESHOLD = 8
:树形阈值,当桶中的元素数量大于该值,并且数组容量大于MIN_TREEIFY_CAPACITY
时,链表结构将转换为树形结构。UNTREEIFY_THRESHOLD = 6
:链表阈值,当桶中的数据少于该值时,树形结构将转换为链表结构。Node<K,V>[] table
:存储数据的数组,数组元素为链表节点。当桶中只有一个元素时,则只存储单独的节点,当桶中元素不止一个时,存储链表和树形结构的首节点。modCount
:记录结构修改次数,以便在迭代器中快速失败。
两个重要的内部类
static class Node<K,V> implements Map.Entry<K,V> {
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;
}
// ……
}
复制代码
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);
}
// ……
}
复制代码
key是怎么确定在数组中的映射位置的?
方法解析参考:定位哈希桶数组索引位置
这里使用位运算的方式,将hashcode的高16为参与运算,是为了降低hash冲突。
// 重新计算hash值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
// 将hashcode与(n-1)进行按位与运算,得出元素在数组中的映射位置
int n = tab.length
int index = (n - 1) & hash;
复制代码
构造函数
- 如果传入了初始容量和负载因子,则使用传入的数据,否则使用默认的数据。
- Hash采用懒加载的形式,构造函数只是初始化了对应属性的值,并没有创建数组,在实际使用时,才会创建数据
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);
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
复制代码
计算扩容阈值
这里计算扩容阈值时,使用的位运算的方式。
/**
* Returns a power of two size for the given target capacity.
*/
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采用懒加载的模式,第一次插入数据时,才会初始化内部数组。
- 如果key对应的位置元素为空,则直接放入;如果为树形结构或链表结构,则按相应规则插入元素到对应的位置。
- 元素添加后,检查扩容阈值,达到阈值,则对数组进行扩容。
- 在将元素插入到链表结构后,需要检查插入后是否需要转换为树形结构。
// 直接添加,如果key存在,则覆盖原来的值
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
// 如果key不存在,才添加
public V putIfAbsent(K key, V value) {
return putVal(hash(key), key, value, true, true);
}
/**
* @param 当前key已有值时,是否覆盖之前的值。
* @param HashMap中,该参数暂时没有使用
*/
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;
// 该key对应的位置没有数据,直接放入。
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
// 查找添加元素的位置 start
Node<K,V> e; K k;
// 该元素在数组中只有一条数据,并且正好,新添加的key与已存在的key相同
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 该key值对应的位置有数据,检查是否为树形节点,如果为树形节点,则说明该位置的数据结构为红黑树,按红黑树的方式进行添加元素
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 该位置对应的数据结构为链表,则按链表的形式进行添加元素:
// 如果链表中已经存在相同的key,则直接使用该地址,否则将新元素添加在末尾
else {
for (int binCount = 0; ; ++binCount) {
// 新添加的key在链表中没有已存在数据,则将数据加载链表末尾
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 检查链表长度是否达到阈值,如果达到阈值在,则进行扩容
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 新添加的key在链表中已存在数据,则使用原来的节点位置
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 查找添加元素的位置 end
// 当key已有值时,是否进行替换
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;
}
复制代码
在树形结构中添加元素 putTreeVal
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
// 找到树形结构的根节点,索引的头节点在某些情况下并不是红黑树的根节点
TreeNode<K,V> root = (parent != null) ? root() : this;
// 遍历树形结构,找到元素添加的位置
for (TreeNode<K,V> p = root;;) {
// 根据红黑树的特性,确定下一个节点的方向,dir为正向右遍历,为负向左遍历,如果为当前元素,则直接返回
int dir, ph; K pk;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
// key的hash值和当前节点的hash值相等,并且节点的key与传入的key也相等时,该节点即为key的映射节点
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
// key的hash值和当前节点的hash值相等(hash冲突),但节点的key与传入的key不相等的情况
// 如果key实现了Comparable<C>接口,并且使用compareTo方法能比较出当前遍历节点的key与传入的key之间的顺序时,则依据该顺序,确定接下来的遍历方向
else if (
(kc == null &&(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
// 如果key没有实现Comparable<C>接口或者调用该接口的compareTo方法比较,两个元素的排序依然相同时,则从该节点从左或向右遍历,如果能找到对应的节点,则直接返回。否则,使用固定规则决定接下来的遍历方向。
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
// 如果该节点的左节点不为空,并且
if (((ch = p.left) != null && (q = ch.find(h, k, kc)) != null)
||((ch = p.right) != null && (q = ch.find(h, k, kc)) != null))
return q;
}
// 使用固定的规则,向左或向右继续遍历
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
// 如果下一个节点为空,说明已经遍历到树的叶子节点,则在当前节点的左边或右边增加新的节点
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node<K,V> xpn = xp.next;
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
if (dir <= 0)
xp.left = x;
else
xp.right = x;
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
// 将树的根节点,移动为头节点
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
复制代码
扩容实现 resize()
n = tab.length
、tab[i = (n - 1) & hash])
,元素在数组中的映射位置与数组的长度相关,所以数组扩容后,需要重新计算每个元素的映射位置。
/**
* HashMap采用懒加载的模式,初始化数组与扩容是同一个方法
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
// 计算新数组的容量和扩容阈值 start
// 当现有数组袁术不为空的情况
if (oldCap > 0) {
// 如果已达到最大容量,则不在进行扩容
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 如果现有数组容量大于默认值,则将数组容量扩大2倍,扩容阈值也扩大2倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// 如果现有数组容量为空,但时扩容阈值不为空,则将容量设置为阈值同等大小
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
// 容量和阈值都使用默认值
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;
// 计算新数组的容量和扩容阈值 end
// 迁移数据到新的数组中
@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;
}
复制代码
扩容后,链表结构重新计算元素位置
例子1:扩容后,节点重 hash 为什么只可能分布在 “原索引位置” 与 “原索引 + oldCap 位置” ?
- 当桶中的数据为链表结构时,对于链表中的每个元素:
- 如果元素的hash值与老表的容量进行与运算,结果为0,则扩容后元素所在新数组中桶的位置与原来一样,即
newTab[j] = loHead
- 如果元素的hash值与老表的容量进行与运算,结果不为0,则扩容后元素所在新数组中桶的位置为
j + oldCap
,即newTab[j + oldCap] = hiHead
- 如果元素的hash值与老表的容量进行与运算,结果为0,则扩容后元素所在新数组中桶的位置与原来一样,即
扩容后,树形结构重新计算元素位置
树形结构,元素位置的计算与链表结构的计算大致相同。
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
TreeNode<K,V> b = this;
// Relink into lo and hi lists, preserving order
TreeNode<K,V> loHead = null, loTail = null;
TreeNode<K,V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
//
for (TreeNode<K,V> e = b, next; e != null; e = next) {
next = (TreeNode<K,V>)e.next;
e.next = null;
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
loTail.next = e;
loTail = e;
++lc;
}
else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
++hc;
}
}
if (loHead != null) {
// 检查长度,小于阈值时,将树形结构转换为链表结构
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
else {
tab[index] = loHead;
if (hiHead != null) // (else is already treeified)
// 重新构建红黑树
loHead.treeify(tab);
}
}
if (hiHead != null) {
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
}
复制代码
获取元素
先找到key所在的桶,如果树形结构,则按照树形结构的方式查找,否则遍历链表查找
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;
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;
}
复制代码
删除元素
基本流程:先找到key对应的元素,然后根据其存储结构(链表、树形、单节点)执行删除
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
/**
* @param matchValue 是否进行值匹配
* @param movable 删除元素后,是否移动其他节点。1. 对于树形结构的元素,在删除指定节点后,是否需要将根节点移动为首节点,2. 如果数组中元素过少,是否将睡醒结构转换为单纯的链表结构
*/
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;
//桶中的第一个节点便是对应的节点
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 {
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;
}
复制代码
树形结构查找元素
final TreeNode<K,V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
// 找到树形结构的根节点
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
// 根据红黑树的规则,查找元素位置。
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
TreeNode<K,V> p = this;
do {
int ph, dir; K pk;
TreeNode<K,V> pl = p.left, pr = p.right, q;
if ((ph = p.hash) > h)
p = pl;
else if (ph < h)
p = pr;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if (pl == null)
p = pr;
else if (pr == null)
p = pl;
else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != 0)
p = (dir < 0) ? pl : pr;
else if ((q = pr.find(h, k, kc)) != null)
return q;
else
p = pl;
} while (p != null);
return null;
}
复制代码
树形结构中删除元素
- 因为树形结构也是以链表实现的,所以对链表的操作同样适合与树形结构
final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
boolean movable) {
// 从链表结构中删除元素-------start
int n;
if (tab == null || (n = tab.length) == 0)
return;
int index = (n - 1) & hash;
// 获取该桶中的首节点
TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
// 获取当当前节点的下一个节点与上一个节点
TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
// 如果当前节点的前节点为空,则说明当前节点是首节点,
// 删除当前节点后,将下一个节点作为首节点,放入桶中
if (pred == null)
tab[index] = first = succ;
else
// 将上一个节点的next节点设置为下一个节点,跳过当前节点
pred.next = succ;
// 将下一个节点的前节点,设置为当前节点的前节点
if (succ != null)
succ.prev = pred;
// 当前链表中,首节点为空,说明当前桶中已经没有了其他元素,结束方法
if (first == null)
return;
// 链表的处理 ------end
// 树形结构处理,
// 如果链表的首节点还存在父节点,则说明:再当前链表中,当前链表的首节点并不是树结构的根节点。
// 这里找出树结构真正的根节点
if (root.parent != null)
root = root.root();
// 如果当前树结构的根节点为空,或者根节点的左右节点为空,
// 则说明桶中的元素已经不足以支撑树形结构,则将树形结构转换为链表结构,不需要在进行后面树形结构的相关的相关操作
if (root == null
|| (movable
&& (root.right == null
|| (rl = root.left) == null
|| rl.left == null))) {
tab[index] = first.untreeify(map); // too small
return;
}
// 树形结构相关调整,从红黑树结构中,删除对应节点,下面代码涉及红黑树删除元素方面的知识,后面再回来研究
TreeNode<K,V> p = this, pl = left, pr = right, replacement;
if (pl != null && pr != null) {
TreeNode<K,V> s = pr, sl;
while ((sl = s.left) != null) // find successor
s = sl;
boolean c = s.red; s.red = p.red; p.red = c; // swap colors
TreeNode<K,V> sr = s.right;
TreeNode<K,V> pp = p.parent;
if (s == pr) { // p was s's direct parent
p.parent = s;
s.right = p;
}
else {
TreeNode<K,V> sp = s.parent;
if ((p.parent = sp) != null) {
if (s == sp.left)
sp.left = p;
else
sp.right = p;
}
if ((s.right = pr) != null)
pr.parent = s;
}
p.left = null;
if ((p.right = sr) != null)
sr.parent = p;
if ((s.left = pl) != null)
pl.parent = s;
if ((s.parent = pp) == null)
root = s;
else if (p == pp.left)
pp.left = s;
else
pp.right = s;
if (sr != null)
replacement = sr;
else
replacement = p;
}
else if (pl != null)
replacement = pl;
else if (pr != null)
replacement = pr;
else
replacement = p;
if (replacement != p) {
TreeNode<K,V> pp = replacement.parent = p.parent;
if (pp == null)
root = replacement;
else if (p == pp.left)
pp.left = replacement;
else
pp.right = replacement;
p.left = p.right = p.parent = null;
}
TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);
if (replacement == p) { // detach
TreeNode<K,V> pp = p.parent;
p.parent = null;
if (pp != null) {
if (p == pp.left)
pp.left = null;
else if (p == pp.right)
pp.right = null;
}
}
if (movable)
moveRootToFront(tab, r);
}
复制代码
HashTable
HashTable是什么?
HashTable
是Map
接口基于哈希表的实现,该接口与 HashMap
大致相似,区别在于HashTable
是线程安全的,并且其值和键都不允许为null。
- 键、值不允许为空。
- 不保证遍历顺序,跟元素的插入顺序和访问顺序无关
- 线程同步。
HashTable
使用synchronized
进行同步,因而对性能有一定的影响 - 除非是迭代器
iterator
本身的remove()
方法,否则不允许在遍历的过程删除元素remove(Object key)
。 - 为基本操作( get和put )提供恒定时间性能。
- 因为不管存还是取都是通过hash函数直接计算出位置,所以说其时间性能是恒定的。
**HashTable**
使用散列表(数组+链表)实现,但是并没有使用红黑树结构。
HashTable
已经不建议使用,在不要求线程安全的情况下使用HashMap
,在要求线程安全的情况下使用ConcurrentHashMap
类图: Dictionary
:一个键值映射的抽象类,类似与Map
。已过时,新接口均建议实现Map
接口
添加元素
- 使用
synchronized
保证线程同步 - 从方法可以看出,键、值为空都将抛出
NullPointerException
- 从方法可以看出,
HashTable
并没有使用红黑树结构,而是单纯的数组+链表实现
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
addEntry(hash, key, value, index);
return null;
}
private void addEntry(int hash, K key, V value, int index) {
modCount++;
Entry<?,?> tab[] = table;
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
rehash();
tab = table;
hash = key.hashCode();
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
}
复制代码
TreeMap
TreeMap是什么?
TreeMap
是基于红黑树的Map
接口的有序实现,该实现的key按照自然顺序或其提供的Comparator
排序。
- 值可以为空,键则根据情况,如果构造函数没有传入
Comparator
实现,则不允许键为空,如果构造函数有传入Comparator
实现,则看具体实现是否允许键为空 - 键的key是要能自然排序的(实现了Comparable接口),否则就要自定义一个比较器Comparator作为参数传入构造函数。所以,key是有序的。
- 线程不安全。
- 除非是迭代器
iterator
本身的remove()
方法,否则不允许在遍历的过程删除元素remove(Object key)
。 - 由于底层是红黑树结构,所以TreeMap的基本操作 containsKey、get、put 和 remove 的时间复杂度是 log(n) 。
- 因为继承了
NavigableMap
,所以可以使用一些导航方法。
类图:
AbstractMap
:提供 Map 接口的骨架实现,以最大限度地减少实现此接口所需的工作量。SortedMap
:在Map
的基础上,对其键提供排序NavigableMap
:基于导航方法,实现SortedMap
接口的抽象类。
TreeMap的具体实现?
TreeMap
内部完全以红黑树的方式实现,以红黑树的方式排列所有的键,因为红黑树本来是有序的,所以TreeMap
也是有序的。- 所以,想要理解
TreeMap
,得先搞懂红黑树。
- 所以,想要理解
构造函数
构造函数可以传入一个实现了Comparator
接口的比较器,如果不穿,则使用默认的比较器,按key的自然顺序排序。
public TreeMap() {
comparator = null;
}
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
public TreeMap(Map<? extends K, ? extends V> m) {
comparator = null;
putAll(m);
}
public TreeMap(SortedMap<K, ? extends V> m) {
comparator = m.comparator();
try {
buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
}
复制代码
添加元素
- 添加元素时,先判断有没有自定义的比较器,如果没有,则使用默认的比较器。
- 按红黑树的规则找出或添加节点。
// 添加单个元素
public V put(K key, V value) {
Entry<K,V> t = root;
// 判断根节点是否存在,如果不存在,则以当前的key创建根节点
if (t == null) {
// 检查是否为为空
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
// 如果构造函数有传入自定义的比较器,则使用自定义比较器,否则使用默认的比较器
Comparator<? super K> cpr = comparator;
if (cpr != null) {
// 按照红黑树的规则,找到指对应的节点
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
else {
// 默认比较器,key不能为空
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);
}
// 如果当前的树中没有对应的节点,则创建新的节点
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
// 添加新的元素后,对红黑树进行平衡处理
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
// 添加多个元素
public void putAll(Map<? extends K, ? extends V> map) {
int mapSize = map.size();
if (size==0 && mapSize!=0 && map instanceof SortedMap) {
Comparator<?> c = ((SortedMap<?,?>)map).comparator();
if (c == comparator || (c != null && c.equals(comparator))) {
++modCount;
try {
// 从已有集合,构建新的红黑树。
buildFromSorted(mapSize, map.entrySet().iterator(),
null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
return;
}
}
super.putAll(map);
}
复制代码
获取元素
按照红黑树的规则,找到指定元素。
public V get(Object key) {
Entry<K,V> p = getEntry(key);
return (p==null ? null : p.value);
}
final Entry<K,V> getEntry(Object key) {
// Offload comparator-based version for sake of performance
if (comparator != null)
return getEntryUsingComparator(key);
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
Entry<K,V> p = root;
while (p != null) {
int cmp = k.compareTo(p.key);
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return p;
}
return null;
}
复制代码
删除元素
先找到指定元素,删除节点,重新平衡红黑树。
public V remove(Object key) {
Entry<K,V> p = getEntry(key);
if (p == null)
return null;
V oldValue = p.value;
deleteEntry(p);
return oldValue;
}
/**
* Delete node p, and then rebalance the tree.
*/
private void deleteEntry(Entry<K,V> p) {
modCount++;
size--;
// If strictly internal, copy successor's element to p and then make p
// point to successor.
if (p.left != null && p.right != null) {
Entry<K,V> s = successor(p);
p.key = s.key;
p.value = s.value;
p = s;
} // p has 2 children
// Start fixup at replacement node, if it exists.
Entry<K,V> replacement = (p.left != null ? p.left : p.right);
if (replacement != null) {
// Link replacement to paren
replacement.parent = p.parent;
if (p.parent == null)
root = replacement;
else if (p == p.parent.left)
p.parent.left = replacement;
else
p.parent.right = replacement;
// Null out links so they are OK to use by fixAfterDeletion.
p.left = p.right = p.parent = null;
// Fix replacement
if (p.color == BLACK)
fixAfterDeletion(replacement);
} else if (p.parent == null) { // return if we are the only node.
root = null;
} else { // No children. Use self as phantom replacement and unlink.
if (p.color == BLACK)
fixAfterDeletion(p);
if (p.parent != null) {
if (p == p.parent.left)
p.parent.left = null;
else if (p == p.parent.right)
p.parent.right = null;
p.parent = null;
}
}
}
复制代码
一些导航方法
firstEntry
lastEntry
pollFirstEntry
pollLastEntry
lowerEntry
lowerKey
floorEntry
floorKey
ceilingEntry
ceilingKey
higherEntry
higherKey
navigableKeySet
descendingKeySet
descendingMap
subMap
headMap
tailMap
subMap
headMap
tailMap
复制代码
总结
HashMap
使用散列表+红黑树实现,使用具有较高的性能,优先使用该类。线程不安全,键值可以为空。HashTable
与HashMap
大致相同,区别在于,前者是线程同步的,使用散列表实现,不允许键值为空。HashTable
使用synchronized
实现线程同步,对性能有一定影响,不建议使用。多线程的环境下建议使用ConcurrentHashMap
TreeMap
是有序的,线程不同步,适用于需要排序的场景。使用红黑树实现,值可以为空,键能不能为空,则看情况。
参考
HashMap就是这么简单【源码剖析】
HashMap源码解析JDK1.8
史上最详细的 JDK 1.8 HashMap 源码解析
Java数据结构之TreeMap