类方法
静态工具方法
- hash
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
- 获取可比较的类的class对象
/**
* Returns x's Class if it is of the form "class C implements
* Comparable<C>", else null.
*/
static Class<?> comparableClassFor(Object x) {
if (x instanceof Comparable) {
Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
if ((c = x.getClass()) == String.class) // bypass checks
return c;
if ((ts = c.getGenericInterfaces()) != null) {
for (int i = 0; i < ts.length; ++i) {
if (((t = ts[i]) instanceof ParameterizedType) &&
((p = (ParameterizedType)t).getRawType() ==
Comparable.class) &&
(as = p.getActualTypeArguments()) != null &&
as.length == 1 && as[0] == c) // type arg is c
return c;
}
}
}
return null;
}
- 也是用来比较的
/**
* Returns k.compareTo(x) if x matches kc (k's screened comparable
* class), else 0.
*/
@SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
static int compareComparables(Class<?> kc, Object k, Object x) {
return (x == null || x.getClass() != kc ? 0 :
((Comparable)k).compareTo(x));
}
- 获取table的size(这个必须是2的整数次幂)
/**
* 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;
}
构造方法
- 指定大小和装载引子
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
}
- 拿别的Map初始化
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
数据结构视图
-
重要的方法:
-
查找方法:
-
外层:(hash & size-1)
-
节点内部:树查找 或
(e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) -
对象hash方法:
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
-
-
查找
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) {//注意这里,桶式存储
//index:(n - 1) & hash
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 {//链表节点就一层层往后找,通过key的比较
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
//暴力O(n*F)的查找
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0) {
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}
在这里能看到:
- 相同hash值的,存储位置都是 (size - 1) & hash,而后通过链表/树状结构,进行存储
修改
添加
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;//如果table数组长度为0或者空就初始化
if ((p = tab[i = (n - 1) & hash]) == null)
//如果hash数组中对应索引的桶是空的就新造一个
//并且由于该位置是空的,因此只要造一个普通的链表头就可以了
tab[i] = newNode(hash, key, value, null);
else {//该位置有桶了,那就对桶进行处理了,下面才是麻烦的地方
Node<K,V> e;//e用来指向该hash桶位置的头
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);
//满足条件就变树 其实这里有个问题:为什么要-1? - > 因为第一个不算进去跳过了
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;
//链表trick
p = e;
}
}
//从上面的for循环中能看到:只有在数据结构中不重复,才会是空
if (e != null) { // existing mapping for key
//swap
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//其实是给linkedHashMap留的实现,默认是空的
afterNodeAccess(e);
return oldValue;
}
}
//注意:此处不检查fail-fast
++modCount;
//大小超过阈值了:就resize
if (++size > threshold)
resize();
//给linkedHashMap留的实现
afterNodeInsertion(evict);
return null;
}
这里能看到:
- 不包含后续操作以及树状节点的话,其实实现就是数组+链表的标准hash表。
- 给LinkedHashMap留了两个口子:
- afterNodeAccess(e)
- afterNodeInsertion(evict)
- 树状节点的查找就放到树节点内部去实现了
- 普通node没有实现查询的方法,本身也比较简单,就原地实现
删除
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)
//可以看到,对于树节点,都是交给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);
}
}
//先找到,找不到就不remove了
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);
//就是链表节点删除,头就指向下一个,不然就是直接把前驱节点的next指向删除节点的next
else if (node == p)
tab[index] = node.next;
else
//上面循环查找的时候,p已经是node的前驱节点了
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
- 整体删除
public void clear() {
Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = 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) {//---------------------(0)
//其实最大的阈值,可以到2^31 -1 ...
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//如果没上面那种情况,直接double
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
//往下指的都是原来数组大小都是空的情况 ---------------(1)
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);
}
//补充一下没初始化的情况:(0)处,(1)处都有可能没有初始化的情况
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) {
//摘下来,让GC一步步工作
oldTab[j] = null;
//其实就是如果是一个单节点,没有后面的尾巴的话,就rehash
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
//树节点就内部拆分了,具体放在哪里?得看树节点的实现方式 //todo
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { //这里就是note里说的情况了:维持顺序
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
//拼lo
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
//拼hi
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
//如果是拼了lo这条,那就直接拼到j上
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
//如果拼了hi这条,那就拼到j+cap上
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
有几个重点:
-
为什么要区分lo和hi?
-
因为在同一个bin中的值,原来的计算索引方式为:
- index = hash & (oldCap-1)
在此处是hash &oldCap,因此值可能不同了
-
-
为什么rehash区分lo和hi,是根据 hash&oldCap==0,而不是oldCap-1?
-
lo为什么不用移动?
- 原因:
- 假设原来位置K上的hash的二进制为:101111,原来的cap为:010000
- 那么,K的索引位置为:101111 & 001111 = 1111,hash&oldCap=0,而且扩容后的那一位恰好是0。
- 扩容后的cap,因为没有到MAX_VALUE,因此cap为:100000
- 那么,K的新索引计算方式为 101111 & 011111 = 1111 ,和原来是一样的
- 因此,如果hash&oldCap==0,那么就放到原来的位置上即可。(resize前后的cap数值,往前多的那一位,对hash&cap-1方法的结果恰好是没影响的)
- 原因:
-
hi为什么是j+oldCap的索引位置?
- 原因:
- 同上面的说法类似:此时假设K位置上hash为:111111
- 如果hash&oldCap!=0,说明新的那一位,原来的hash值上刚好有。
- (111111 & 010000 = 0100000)
- 那么,hash & newCap-1 , 刚好比原来在前面的位置多一位
- (111111 & 001111 = 001111)
- (111111 & 011111 = 011111)
- 刚好是比原来的多了 010000,即:OldCap的值
- 因此,如果hash&oldCap!=0,index = j+oldCap
- 原因:
次层容器
树状化
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//这里就是上面注释里说的:如果太小了干脆就别变树了,变大一次看看
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;//hd-结果,tl-迭代指针
do {//将链表变成树的结构
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)//赋值,同时树化容器
//其实这一步只看到这里不是很清楚是在干什么,需要树节点中去看
hd.treeify(tab);
}
}
//其实就是搞个新的,写个代理方法罢了
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}
内容视图
获取key
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}
获取value
public Collection<V> values() {
Collection<V> vs = values;
if (vs == null) {
vs = new Values();
values = vs;
}
return vs;
}
获取键值对
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
1.8相关方法
把Map里的1.8新加的方法都实现了一遍,没有什么新的特性,就是新瓶装老酒。
容器的对象属性
Clone()
loadFactor()
capacity() ()->return (table != null) ? table.length :
(threshold > 0) ? threshold :
DEFAULT_INITIAL_CAPACITY;
writeObject
readObject
- 值得注意的一个地方,是这些容器都支持从流直接写入内存并格式化(writeObject,readObject)。