HashMap类中的put方法负责将元素添加到HashMap中,它通过调用名为addEntry的方法来实现,其代码如下:
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);
}
正如您在此方法中所看到的,如果超过了阈值,则会调整HashMap的大小,因此我建议尝试扩展HashMap类并编写自己的put
和addEntry
方法以删除调整大小。可以尝试以下代码:
package java.util;
public class MyHashMap<K, V> extends HashMap {
private V myPutForNullKey(V value) {
for (Entry<K, V> e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
myAddEntry(0, null, value, 0);
return null;
}
public V myPut(K key, V value) {
if (key == null)
return myPutForNullKey(value);
if (size < table.length) {
int hash = hash(key.hashCode());
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++;
myAddEntry(hash, key, value, i);
}
return null;
}
void myAddEntry(int hash, K key, V value, int bucketIndex) {
Entry<K, V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K, V>(hash, key, value, e);
size++;
}
}
由于put
和addEntry
无法重写,您需要编写自己的方法,并且您还需要对putForNullKey
执行相同的操作,因为它在put
内部调用。在put
中需要进行验证以验证我们是否尝试在表已满时放置对象。