1.jdk1.7 HashMap
The data structure of hashMap: array + linked list
Initial value of ArrayList: 10
Why not use the add method of list in hashMap. HashMap is a key-value structure. When getting (key), you need to traverse the entire array, which is not as efficient as list.get (subscript).
put operation:
1. Use the hashcode to find the length of the remainder array to get the subscript value of the index array
2. Put the new Entry element into table[index]
1.1 Construction method
Construction method, the default initial memory is 16, and the default parameter DEFAULT_LOAD_FACTOR=0.75f. I don't know what's the use, continue to analyze
Default initial capacity: static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;Default maximum capacity: static final int MAXIMUM_CAPACITY = 1 << 30;Default parameters: static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 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
}
1.2 put method (TODO)
The put operation is roughly divided into the following steps.
1. The initial capacity is the power of 2
2. Put it in the first position as empty
3. Hash operation, & operation to traverse the key value to get the value value
4. Judging the conditions to expand the capacity, create a new entry<key,value> and put it into the entry[] array.
^=XOR operation, the same is 1, not the same is 0
|= The bitwise AND operation is different to 1, and the same is 0 or 1
&=Bitwise and post-assignment is different to 0, the same is the same value
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);//初始化容量为2的冥次方
}
if (key == null)
return putForNullKey(value);//将null值放入第一个位置
int hash = hash(key); //hash运算
int i = indexFor(hash, table.length);//&运算
for (Entry<K,V> e = table[i]; e != null; e = e.next) {//遍历返回值
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);//将key,value放入entry
return null;
}