/**
* 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){returnputVal(hash(key), key, value,false,true);}/**
* 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;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))))
e = p;elseif(p instanceofTreeNode)
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 1sttreeifyBin(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;}
HashMap GET实现
计算key的hash
hash计算数组的index
找出index的节点
第一个节点hash和key相等,直接返回first node
不相等
是否为红黑树,是则在树中查找
链表,则遍历链表,找出节点
public V get(Object key){
Node<K,V> e;return(e =getNode(hash(key), key))== null ? null : e.value;}/**
* Implements Map.get and related methods.
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/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){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 instanceofTreeNode)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;}