Map
这部分可以参见官方文档的介绍
view
有意思的是这个 视图集 View,
- keySet — the Set of keys contained in the Map.
- values — The Collection of values contained in the Map. This Collection is not a Set, because multiple keys can map to the same value.
- entrySet — the Set of key-value pairs contained in the Map. The Map interface provides a small nested interface called Map.Entry, the type of the elements in this Set.
注意 values 并不是一个 Set 而是一个Collection
multimap
Map里并没有实现 multimap,不过它提供了一种很简单的实现方式,即把key 与一个 list对应。
Map.entry
JDK 1.8 更新了几个提供比较器的方法,用它完全可以实现 类似c++中的 pair
;
public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> c1.getKey().compareTo(c2.getKey());
}
public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> c1.getValue().compareTo(c2.getValue());
}
public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
Objects.requireNonNull(cmp);
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
}
public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
Objects.requireNonNull(cmp);
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
}
HashMap
HashMap
底层是一个长度为
的数组,数组元素是key-value 的Entry
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;
这在取模运算的时候有一个非常好的优势,可以用 与 运算代替代替模运算。带来常数的优化。可是同时的缺点就是这个 hash 值在取模的时候仅会保留低位,高位的不同完全被忽略,所以真正计算hash的时候,他是将key
异或上了(h>>16
)
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);//低位变化
}
冲突解决策略
有趣的是这里解决冲突的时候不是在这个 table
中用线性或者平方探测找下一个位置,而将每一个 bin(桶,table的单元)做成一个 链表,并且为了解决链表元素过高插入和寻找比较难的问题,他会将在链表的size大于某个特定值(8)的时候,组织成一颗红黑树, 保证
的时间优化,
是冲突的元素个数。
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;
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))))//bin首元素,直接修改
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;
}
resize 的策略
- risize就是将 table 的大小乘以2
- risize 的时候会涉及再hash的问题,这在这里面也很简单,映射到同一个桶的元素仅会被hash到同一个方,或者原来的桶的位置加上原来的容量。即在最高位发生变化
- 还有一个问题是当在hash之后链上元素小于固定值的时候会将它从红黑树展开为链表
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
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)
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;// 重新hash分为两部分高位j+oldCap,和低位j
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 {// e idx of e + oldCap, 属于重新hash后的高位bin
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;
}
迭代器策略
正如你所想的一样,当做 for-each
的遍历的时候它所做的遍历次数并不是恰好等于元素个数,而是等于箱子的个数,即会浪费一定的变量时间,不过好在默认情况下装箱的因子 loadFactor = 0.75
相当于浪费
的时间
abstract class HashIterator {
Node<K,V> next; // next entry to return
Node<K,V> current; // current entry
int expectedModCount; // for fast-fail
int index; // current slot
HashIterator() {
expectedModCount = modCount;
Node<K,V>[] t = table;
current = next = null;
index = 0;
if (t != null && size > 0) { // advance to first entry
do {} while (index < t.length && (next = t[index++]) == null);//遍历数组,找到一个非空的桶
}
}
public final boolean hasNext() {
return next != null;
}
final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);//遍历数组,找到一个非空的桶
}
return e;
}
public final void remove() {
Node<K,V> p = current;
if (p == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
current = null;
K key = p.key;
removeNode(hash(key), key, null, false, false);
expectedModCount = modCount;
}
}
LinkedHashMap
LinkedHashMap
就是继承自 HashMap
的类了 它并没有重写put, 而是选择了重写 Node, 并且改写自己在 HashMap 调用put 方法时和 node相关的方法就行了,因为hashMap本来就是设计成的list解决冲突不过在元素多的时候改成了红黑树节点而已。