HashMap内部是一个数组,每个一个元素是一个Entry(LinkedList)。如果当前索引已经有值,遍历当前的Entry,判断 key.equals(k) ,如果是true,replace value. 否则就检查Entry的next, until Entry.next == null, store value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
st=>start
key_is_null=>condition: key != null?
hashcode=>operation: hashCode(),hash();
indexFor=>operation: indexFor();
index=>operation: indexFor();
store=>operation: put talbe[0];
exist=>condition: iterator, key.equals(k)?
replace=>operation: replace value;
put=>operation: put value;
e=>end
st->key_is_null
key_is_null(no)->store(right)->e
key_is_null(yes)->hashcode->indexFor->exist
exist(yes)->replace->e
exist(no,left)->put(right)->e
get()方法解析
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* 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><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){
if (key == null)
return getForNullKey();
int hash = hash(key.hashCode());
for (Entry<K , V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {