注: 以下代码均来自Java8
HashMap(LinkedHashMap)
JDK 1.8 对 HashMap 进行了比较大的优化,底层实现由之前的 “数组+链表” 改为 “数组+链表+红黑树”。下面先看看基本属性:
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
private static final long serialVersionUID = 362498820763181265L;
// 默认容量16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 链表转红黑树的阈值,大于该值,即9个节点时,转红黑树
static final int TREEIFY_THRESHOLD = 8;
// 红黑树转链表的阈值,小于该值,即只有5个节点时,转链表
static final int UNTREEIFY_THRESHOLD = 6;
// 转红黑树时, table的最小长度
static final int MIN_TREEIFY_CAPACITY = 64;
// 存储节点的数组,即hash桶
transient Node<K,V>[] table;
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
*/
transient Set<Map.Entry<K,V>> entrySet;
// key-value 的映射个数,map的大小
transient int size;
// 新增和删除元素的次数,不包含修改的次数
transient int modCount;
// 扩容阈值,loadFactor * 当前最大容量,大于该值时,扩容
int threshold;
// 负载因子
final float loadFactor;
注:参数 TREEIFY_THRESHOLD 和 MIN_TREEIFY_CAPACITY 需要同时满足才能转成红黑树,当然这在开发工程中实际上是应该是遇不到的场景,如果存在,那说明key对象的实现存在问题,需要反思,为什么会出现大量key在相同的hash桶中。
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; // 首次添加数据时,通过resize()初始化table数组
if ((p = tab[i = (n - 1) & hash]) == null) // 查找key所在的hash桶
tab[i] = newNode(hash, key, value, null); // key所在的hash桶为空时,直接创建一个节点作为hash桶的第一个节点
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)
// 所在hash桶是红黑树时,添加一个树节点进红黑树中
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
// 若当前链表长度已超过8,则链表转红黑树
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
// 已存在的key时,替换对应的value值
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize(); // 当前size大于扩容阈值时,进行扩容
afterNodeInsertion(evict);
return null;
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
注:1.hash值计算:key的hash值与自身无符号右移16位的值,进行按位异或的结果。
2.hash桶查找:当前的将 (table.length - 1) 与上述hash结果进行按位与(&)运算,结果为hash桶的位置。
get操作:
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);
}
}
// table为null,或长度为0,或找不到对应的key时,返回null
return null;
}
remove操作:
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;
// 查找节点
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; // 返回删除的节点
}
}
// 节点不存在时,返回null
return null;
}
resize操作:
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
}
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;
@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)
// 只有一个节点时,直接放入新的hash桶的首节点
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// 将当前红黑树节点分成上下两个节点,分别存储在j和j+oldCap两个位置
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
// 将当前链表节点分成上下两个节点,分别存储在j和j+oldCap两个位置
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
// 判断当前node的hash高一位是否为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;
}
LinkedHashMap
继承自 HashMap,并在此基础上维护了双向链表
public class LinkedHashMap<K,V>
extends HashMap<K,V>
implements Map<K,V>
{
/**
* HashMap.Node subclass for normal LinkedHashMap entries.
*/
static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
private static final long serialVersionUID = 3801124242820219131L;
// 双向链表头节点
transient LinkedHashMap.Entry<K,V> head;
// 双向链表尾节点
transient LinkedHashMap.Entry<K,V> tail;
// 是否访问排序
final boolean accessOrder;
注:访问排序 accessOrder 为 true 时,会按照最近访问进行元素排序,即:最新访问的元素放在链表尾部。
Hashtable(Properties)
HashMap 和 Hashtable 的区别
- HashMap 允许 key 和 value 为 null,Hashtable 不允许。
- HashMap 的默认初始容量为 16,Hashtable 为 11。
- HashMap 的扩容为原来的 2 倍,Hashtable 的扩容为原来的 2 倍加 1。
- HashMap 是非线程安全的,Hashtable是线程安全的。
- HashMap 的 hash 值重新计算过,Hashtable 直接使用 hashCode。
- HashMap 继承自 AbstractMap 类,Hashtable 继承自 Dictionary 类。
Properties
继承自 Hashtable,并在此基础上新增 load 和 store 方法,用于读取和写入 properties 文件。
TreeMap
TreeMap 底层通过红黑树实现,可实现定制排序或自然排序。
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
{
// 用于TreeMap排序的Comparator函数接口,为null时默认使用key的compareTo进行排序
private final Comparator<? super K> comparator;
// 跟节点
private transient Entry<K,V> root;
// map的大小
private transient int size = 0;
// map新增或删除元素的次数
private transient int modCount = 0;
注:1.若comparator参数为null,并且key对象的类未实现Comparable接口时,会报错 ClassCastException。
TreeMap 和 HashMap 的区别
1.数据结构不同:
a.HashMap 通过hash表,底层由数组+链表+红黑树实现,使用hash计算桶的下标,发生hash冲突时,会以链表或红黑树将这些元素连接起来,不保证顺序;
b.TreeMap 只由红黑树实现,根据 key 进行排序,插入或删除元素时,会重新调整红黑树的结构。
2.性能对比:
a.HashMap:
insert:平均为 O(1),最坏情况可能退化成 O(n);
delete:平均为 O(1),最坏情况可能退化成 O(n);
search/get:平均为 O(1),最坏情况可能退化成 O(n)。
b.TreeMap:
insert:每次将节点插入到红黑树中,时间复杂度平均为 O(logN);
delete:删除节点后调整节点替代者连接以保持树的性质,时间复杂度平均为 O(logN);
search/get:二分查找,时间复杂度平均为 O(logN)。
注:从时间复杂度角度看,HashMap 插入、删除和随机访问元素都具有常数复杂度 O(1),但并不保证最坏情况下的稳定性;而 TreeMap 的插入、查询和删除操作的时间复杂度都为 O(logN),稳定性更好,但在数据量较大时表现可能会相对较差。此外,HashMap 在考虑键值映射唯一性时需要考虑键值的 HashCode 计算和哈希函数冲突问题,而 TreeMap 没有这个问题。
3.等价比较:
HashMap
判断两个键是否“相等”的标准是 hashCode()
和 equals()
方法,而 TreeMap
判断两个键是否“相等”的标准是 comparator()
或 compareTo()
方法。所以TreeMap的等价比较会更加的灵活点。
4.选型建议:
对于在Map中插入、删除和定位元素这类操作,HashMap是最好的选择。然而,假如你需要对一个有序的key集合进行遍历,TreeMap是更好的选择。基于你的collection的大小,也许向HashMap中添加元素会更快,将map换为TreeMap进行有序key的遍历。
a.对于少量数据元素的存储,使用 TreeMap 合适(O(NlogN) 的常数较小)。
b.对于元素数量相对更多的场景,可以使用 hash 实现的 HashMap(O(1) 的时间复杂度)