创建HashMap
要使用HashMap首先就要实例一个对象出来。
HashMap<String, Integer> h = new HashMap<>();
跳进去看看
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
代码很简单就是给loadFactor赋了个默认值0.75。loadFactor叫加载因子,目前还不知道,它是干什么的,先暂时不管。
存入新键值对
这是我们很熟悉的操作。
h.put("key0",1011);
跳进去看看
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
可以看到代码也很简单,就是调用了putVal方法,再看看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);
}
这里将原来的key值传了进来(key本身也是一个对象),如果为空就返回哈希值0,否则就在key原有哈希值的基础上再进行16位的无符号右移,从而获得了一个新的哈希值,把它作为返回值。
接下来跳进putVal方法看看。
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
\\A
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
\\B
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;
}
代码开始变复杂了,我在上面用字母把代码分成了将各部分,一点一点来分析。
首先分析A代码块
...
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
...
/**
* 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;
table是HashMap的一个成员变量,键值对的值(value)就是存储在table里的,可以看到table是一个数组,也就是说值是用数组来存储的。注释里写道在必要的时候会重新规定table大小,而数组大小本身固定不变的,所以table扩容时必然会有copy操作,这在后面会分析。
回到代码块A,代码很简单,如果table为空或容量为0就调用resize方法。resize字面意思就是重新规定大小,跳进去这个方法看看。
代码将近100行,一点一点分析。
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
//1
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//2
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;
//3
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
...
代码块1:table的容量已经超出最大限定,阈值就改为Integer的最大值。
代码块2:容量左移1位(也就是扩大一倍),在新容量没有超出最大限定以及原容量超出默认初始容量时,阈值也扩大一倍。
代码块3:只有在原容量及原阈值都为0时才会进入代码块3,可以分析出这里进行的是初始化操作。这里我们再次看到了前面代码出现的加载因子(DEFAULT_LOAD_FACTOR 0.75),新阈值为默认初始化容量的75%。
阈值其实就是一个临界值、警告值,也就是说达到这个值势必要进行某些操作。达到容量的阈值后进行的操作猜应该是扩容了,继续看代码。
...
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
...
果然,下面就new了一个新的数组,容量大小为扩容后的大小。但这仅仅是申请一个数组空间,里面还是空的,所以要把所有的value都转移到这个新数组上,代码较长,分析重点。
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;
...
将原来存储value的数组遍历一遍,可以看到这里进行的并不是简单的转移操作,例如一个value原来所在的位置是5,转移后的位置可能不是5,这里可能不好理解,其实这是处理冲突后的结果。
例如A,B最初都要插入table[6]这个位置,这就冲突了,于是B就要运行某些算法来找新的插入位置,但要注意,既然放得进就要找的回。计算机HashMap冲突处理方法其实有很多种,感兴趣的同学可以自行查阅相关资料。
纵观resize方法,其实它做的事很简单,形象的说就是换个更大的家,把原来的家具搬到新家,至于家具的摆放位置可能与原来的不一样。
这样一来,putVal的A代码块就走完了,其实它做的就是检查容量,再分析B代码块。
...
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else{
...
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
这里就真正是键值对插入操作了。如果插入的数组位置是空着的,那就直接插入就可以了,插入之后可能达到容量阈值,这时就需要扩容了。
那键值对已经存在了呢?继续往下看。
...
Node<K,V> e; K k;
//1
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
...
//2
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
...
当1处得知新put进来的键值对已经存在时就先暂存下来,留到2处处理。
代码块2可以看出如果允许更改值,就把原先的value替换为新value,这么一来整个put就算是走了一遍了。
取值
取值的基本操作也是我们所熟悉的了,跳进去看看原理
...
Integer value = h.get("key0");
...
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @see #put(Object, Object)
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
代码很简单,就是去找key值,存在就把对应的value值返回,否则返回null。