Map
- 我们先看一下官方的注释:
An object that maps keys to values. A map cannot contain duplicate keys;
* each key can map to at most one value.
简单解释一下:将键映射到值上,Map不能包含重复的键,每个键最多只能映射一个值。
- Map是Map家族的顶层接口,它规范了作为Map家族的基本方法
- Map与List,与Set不同,它没有父接口,它自己就是顶层接口。
- Map家族包含的成员很多,最主要的成员有:HashMap、ThreeMap。
HashMap
基于java1.8分析
- 我们看一下官方的注释:
Hash table based implementation of the <tt>Map</tt> interface. This
* implementation provides all of the optional map operations, and permits
* <tt>null</tt> values and the <tt>null</tt> key. (The <tt>HashMap</tt>
* class is roughly equivalent to <tt>Hashtable</tt>, except that it is
* unsynchronized and permits nulls.) This class makes no guarantees as to
* the order of the map; in particular, it does not guarantee that the order
* will remain constant over time.
简单解释一下:HashMap允许键和值为null,但是它不是线程同步的,它也不保证集合中元素的顺序,不保证随着时间的移动集合中元素的顺序。
- HashMap储存信息的方式如下图:
源码
- HashMap包含的一些成员变量:
// 默认初始化的容量,必须是2的幂
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 最大容量,必须是2的幂
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;
// 存放的元素的个数,不等于数组大小
transient int size;
// hashMap结构发生变化的次数
transient int modCount;
// 当前阈值
int threshold;
// 当前加载因子大小
final float loadFactor;
HashMap包含的一些基本方法
- HashMap有一个内部类Node,通过该节点实现单链表。
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;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
- 数组对应索引下面的结点的个数超过树化阈值的时候,单链表转化成红黑树,下面是红黑树的结点的部分源码:
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);
}
/**
* Returns root of tree containing this node.
*/
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
······
}
- HashMap 对外提供的put()方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
我们可以看见,put()方法调用了putVal()方法,在传参的时候调用了hash()这个方法,我们先去看看hash()这个方法。
static final int hash(Object key) {
int h;
// 先把hash值右移16位,再与hash值进行异或运算,保证高十六位也能参加运算,从而散的更开。
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
这是一个静态方法,当key为null的时候返回0,否则要调用hashCode()这个方法进行计算,返回一个hash值。这个方法完了,我们往下走看看putVal()这个方法。
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;
// 通过使用数组的长度和hash值的与运算(实际上等同于hash%n)找到该存入数据的下标
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//判断key是否相同
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;
}
}
//替换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;
}
下面是插入的流程:
- 插入元素的过程中可能会涉及扩容的操作,我们看看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;
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
//第一次初始化HashMap,容量和阈值都用默认的
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)
// 取余找到下标,把结点转移到扩容后的数组
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;
//这里进行与运算是判断结点放在扩容后的数组中是否需要移动位置,
0:不移动
不为0:移动(新的下标是j+oldCap)
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;
}
- HashMap的查找方法
public V get(Object key) {
Node<K,V> e;
//调用了getNode()方法
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
这里调用了查找结点的方法getNode()我们去看看
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
// 判断 HashMap被初始化过且传入的hash值有对应的结点
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;
}
- HashMap的删除方法remove()
public V remove(Object key) {
Node<K,V> e;
//查找要删除的结点
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
这里主要调用了removeNode(),我们去看看这个方法干了什么。
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;
//判断HashMap被初始化过且传入的hash值有对应的结点
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;
}
以上就是HashMap的插入、扩容和删除方法。
接下来我们就谈谈对于HashMap的遍历的方式:
- 1 通过HashMap的继承自父类的成员变量values(AbstractCollection<V>)来遍历HashMap的所有value值。
private Map<String,String>mMap = new HashMap<>();
Collection<String>values = mMap.values();
for(String value : values){
System.out.println(value);
}
- 2 通过HashMap的继承父类的成员变量keySet(AbstractSet<K>)来遍历所有的key值,可通过二次遍历获取value值。
private Map<String,String>mMap = new HashMap<>();
Set<String >keySet = mMap.keySet();
//foreach 遍历
for(String key : keySet){
System.out.println(key);
System.out.println(mMap.get(key));
}
//迭代器遍历
Iterator<String>it = keySet.iterator();
while(it.hasNext()){
String key = it.next();
System.out.println("[ " + key + "," + mMap.get(key) + " ]" );
}
- 3 通过HashMap的成员变量entrySet(AbstractSet<Map.Entry<K,V>>)可以一次遍历key和value。
private Map<String,String>mMap = new HashMap<>();
Set entrySet = mMap.entrySet();
Iterator it = entrySet.iterator();
while(it.hasNext()){
Map.Entry<String,String> entry = (Map.Entry<String,String>)it.next()
System.out.println("[ " + entry.getKey() + "," + entry.getValue() + " ]" );
}
- 4 通过java1.8新增的方法foreach()
private Map<String,String>mMap = new HashMap<>();
mMap.forEach(new BiConsumer<String, String>() {
@Override
public void accept(String key, String value) {
System.out.println("[ " + key + "," + value + " ]" );
}
});