/**
* 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);
上面是hashMap的一段源码,int n,i; n是没有初始化但是怎么可以n-1呢?
In the first if judgment
1. If the previous item ((tab=table)==null) is true, then directly execute the statement in the if and assign a value to n
2. If the previous item is false, then Just assign a value to n (n=tab.length) first, and then determine whether it is equal to 0 (equivalent to n==0)
--2.1 If n==0 is true, then execute the statement in if
--2.2 If n==0 is false, then n will remain unchanged and the value is tab.length
In fact, it is equivalent to the following string
You should be able to understand this. .
The logic is that if the tab array is null or has a length of 0, then let tab equal the return value of the resize() method, and let n equal the length of tab
If tab is not null or the length is greater than 0, then n is also Same as the length of tab
The assignment operation in the condition is also an assignment operation