1.jdk1.7 HashMap
hashMap的数据结构:数组+链表
ArrayList的初始值:10
hashMap中为什么不用list的add方法,hashMap是key-value结构,在get(key)时需要遍历整个数组,效率上不如list.get(下标)效率高
put操作:
1.使用hashcode求余数组长度得出index数组下标值
2.new Entry元素放入table[index]中
1.1 构造方法
构造方法,默认初始内存16,默认参数DEFAULT_LOAD_FACTOR=0.75f。不知道有什么用,继续解析
默认初始容量:static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;默认最大容量:static final int MAXIMUM_CAPACITY = 1 << 30;默认参数: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方法(TODO)
put操作大致分为以下几步。
1. 初始化容量为2的次方
2. 为空放到第一个位置
3.hash运算,&运算遍历key值得到value值
4. 判断条件进行扩容操作,新建entry<key,value>放入entry[]数组中。
^=异或操作,相同为1,不相同为0
|=按位与操作 不同为1,相同为0或者1
&=按位与后赋值 不同为0,相同为相同的值
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;
}