这里写目录标题
死磕Map
面试Java,集合框架中的Map一定是绕不过的一个坎儿,今天就让我们从是什么,为什么,怎么用这三面来死磕Map。
Map接口及基本实现类
Map是什么?
简而言之,Map就是Java中提供的保存键值对的数据结构。
Java类库中提供的Map的基本实现
类型 | 特点 |
---|---|
HashMap* | Map基于散列表的实现(它取代了HashTable)。插入和查询“键值对”的开销是固定的。可以用于通过构造器设置容量和复杂因子,以调整容器性能 |
LinkedHashMap | 类似于HashMap,但是迭代遍历它时,取得“键值对“的顺序是插入顺序,或者是最近最少使用(LRU)的次序。只比HashMap慢一点;在迭代访问时反而更快,因为使用链表维护内部次序 |
TreeMap | 基于红黑树的实现。查看“键”或“键值对”时,它们会被排序(次序由Comparable或Comparator决定) |
WeakHashMap | 弱键(weak key)映射,允许释放映射所指向的对象;如果映射之外没有引用指向某个“键“,则此键可以被垃圾回收器回收 |
ConcurrentHashMap | 一种线程安全的Map |
IdentityHashMap | 使用==代替equals()对“键”进行比较的散列映射。转为解决特殊问题而设计的 |
本文只讨论前三个Map的实现类,而ConcurrentHashMap会在之后的并发容器一文中专门讨论。
Map的底层原理剖析
HashMap底层实现
底层数据结构
HashMap的底层数组结构为数组加链表,不过JDK1.7和JDK1.8略有不同
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 初始化桶的大小
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;//红黑树转为链表的阙值
static final int MIN_TREEIFY_CAPACITY = 64;
transient Node<K,V>[] table;//桶,存放数据的数组
//节点
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> 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;
}
}
负载因子:
给定的默认容量为 16,负载因子为 0.75。Map 在使用过程中不断的往里面存放数据,当数量达到了 16 * 0.75 = 12 就需要将当前 16 的容量进行扩容,而扩容这个过程涉及到 rehash、复制数据等操作,所以非常消耗性能。因此通常建议能提前预估 HashMap 的大小最好,尽量的减少扩容带来的性能损耗。
put的过程
- 判断当前数组是否需要初始化。
- 计算元素在在桶中的位置,如果没有元素,则直接插入。
- 否则计算元素在链表中需要插入的位置。
- 如果是链表则插入,如果为红黑树则插入红黑树。
- 如果当前为链表插入后大于转红黑树的阙值,则插入后转为红黑树
- 如果插入的值已在链表中存在则覆盖。
- 如果插入后计算是否需要对桶进行扩容。
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;
}
remove的过程
- 通过hashCode映射计算元素在桶中的位置
- 链表或红黑树树中查找该元素
- 找到该元素后删除
- 删除后判断是否需要缩容
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;
}
为什么链表长度大于8 的时候要转为红黑树
红黑树的平均查找长度是log(n),长度为8,查找长度为log(8)=3,链表的平均查找长度为n/2,当长度为8时,平均查找长度为8/2=4,这才有转换成树的必要;链表长度如果是小于等于6,6/2=3,虽然速度也很快的,但是转化为树结构和生成树的时间并不会太短。
还有选择6和8的原因是:
中间有个差值7可以防止链表和树之间频繁的转换。假设一下,如果设计成链表个数超过8则链表转换成树结构,链表个数小于8则树结构转换成链表,如果一个HashMap不停的插入、删除元素,链表个数在8左右徘徊,就会频繁的发生树转链表、链表转树,效率会很低。
参考链接:为什么jdk8的HashMap链表的长度超过8会转换成红黑树?
TreeMap的底层实现原理
TreeMap底层采用红黑树实现
红黑树的实现参考博客:红黑树(一)之 原理和算法详细介绍
public V put(K key, V value) {
Entry<K,V> t = root;
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 {
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;
}
LinkedHashMap底层实现
LinkedHashMap有以下特点
(1)使用链表存储,保证了它的有序性,这也是区别HashMap的地方
(2)它具有HashMap的特性,能以O(1)的复杂度查找到某个元素。
(3)LinkedHashMap还可以根据访问的顺序进行排序(注意是在插入顺序基础上进行排序)。
public class LinkedHashMap<K,V>
extends HashMap<K,V>
implements Map<K,V>{
//存储数据是一个Entry的双向链表
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);
}
}
//双向链表的链表头
transient LinkedHashMap.Entry<K,V> head;
//双向链表的链表尾部,记录最新被修改的元素
transient LinkedHashMap.Entry<K,V> tail;
//是否排序
final boolean accessOrder;
//获取元素,如果acceOrder为true,每次通过get获取该元素后将其放到链表的末尾
public V get(Object key) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) == null)
return null;
if (accessOrder)
afterNodeAccess(e);
return e.value;
}
void afterNodeAccess(Node<K,V> e) { // move node to last
LinkedHashMap.Entry<K,V> last;
if (accessOrder && (last = tail) != e) {
LinkedHashMap.Entry<K,V> p =
(LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
p.after = null;
if (b == null)
head = a;
else
b.after = a;
if (a != null)
a.before = b;
else
last = b;
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
tail = p;
++modCount;
}
}
}
基本使用
代码来源:Java编程思想第四版
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author wq
*/
class CountingMapData
extends AbstractMap<Integer,String> {
private int size;
private static String[] chars =
"A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
.split(" ");
public CountingMapData(int size) {
if (size < 0) this.size = 0;
this.size = size;
}
public Set<Map.Entry<Integer,String>> entrySet() {
// LinkedHashSet retains initialization order:
Set<Map.Entry<Integer,String>> entries =
new LinkedHashSet<Map.Entry<Integer,String>>();
for(int i = 0; i < size; i++)
entries.add(new Entry(i));
return entries;
}
private static class Entry
implements Map.Entry<Integer, String> {
int index;
Entry(int index) {
this.index = index;
}
public boolean equals(Object o) {
return Integer.valueOf(index).equals(o);
}
public Integer getKey() {
return index;
}
public String getValue() {
return
chars[index % chars.length] +
Integer.toString(index / chars.length);
}
public String setValue(String value) {
throw new UnsupportedOperationException();
}
public int hashCode() {
return Integer.valueOf(index).hashCode();
}
}
}
public class Maps {
public static void printKeys(Map<Integer,String> map){
System.out.println("Size="+map.size()+",");
System.out.println("Keys: ");
for(int e: map.keySet()){
System.out.print(e+" ");
}
System.out.println();
}
public static void printValues(Map<Integer,String> map){
System.out.println("Size="+map.size()+",");
System.out.println("Values: ");
for(String s: map.values()){
System.out.print(s+" ");
}
System.out.println();
}
public static void test(Map<Integer,String> map){
System.out.println(map.getClass().getSimpleName());
map.putAll(new CountingMapData(25));
map.putAll(new CountingMapData(25));
printKeys(map);
printValues(map);
System.out.println("map.containsKey(11):"+map.containsKey(11));
System.out.println("map.get(11)"+map.get(11));
System.out.println("map.containsVlaue(\"F0\"):"+map.containsValue("F0"));
Integer key=map.keySet().iterator().next();
System.out.println("First key in map:"+key);
map.remove(key);
printValues(map);
map.clear();
System.out.println("map.isEmpty():"+map.isEmpty());
map.putAll(new CountingMapData(25));
map.keySet().removeAll(map.keySet());
System.out.print("map.isEmpty():"+map.isEmpty());
}
public static void main(String[] args) {
test(new HashMap<Integer,String>());
test(new TreeMap<Integer,String>());
test(new LinkedHashMap<Integer,String>());
test(new IdentityHashMap<Integer,String>());
test(new ConcurrentHashMap<Integer,String>());
test(new WeakHashMap<Integer,String>());
}
}