1.构造器
不难可以看出HashMap的存储是由entry数组组成的,默认大小16。
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
table = new Entry[DEFAULT_INITIAL_CAPACITY];
init();
}
2.put
hashmap中存储数据,如果key为null,总是存入Entry[0]中。
先算出key的hash值,再调用indexFor算出数组下标值,再放入相应的table[i].
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = <span style="color:#ff0000;">hash(key.hashCode())</span>;
int i = <span style="background-color: rgb(255, 0, 0);">indexFor(hash, table.length);</span>
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++;
<span style="background-color: rgb(255, 0, 0);">addEntry(hash, key, value, i);</span>
return null;
}
static int indexFor(int h, int length) {
return h & (length-1);
}
当indexFor算出来的下标值一样时,是否会造成覆盖的危险呢?
答案当然是否定的,HashMap中用到链式存储的方式,例如,C<Entry>.next = B<Entry> ,B<Entry>.next = A<Entry> ,
所以说table数组中存储的的是最后插入的元素,不存在覆盖的危险。
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
if (size++ >= threshold)
resize(2 * table.length);
}
3.get
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) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}
4. resize
HashMap的公共溢出区的实现如下:
当哈希表的容量超过shreshold的时候,hashmap开始扩容,并创建一张新表,将原表的数据映射到新表中。
当哈希表接近等于Integer最大值的时,hashmap的容量也开始接近于2的30次方,将不在扩容。
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Entry[newCapacity];
transfer(newTable);
table = newTable;
threshold = (int)(newCapacity * loadFactor);
}
综上所述,用以下方法解决hash冲突,
- 开放定址法(线性探测再散列,二次探测再散列,伪随机探测再散列)
- 再哈希法
- 链地址法
- 建立一个公共溢出区