答案出乎意料地是。我将 Sysout 放在 put() 的代码中以观察它的行为
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
System.out.println("Put: Table empty. Inflating table to threshold:" + threshold);
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
System.out.println("Put: Key not null:" + hash);
int i = indexFor(hash, table.length);
System.out.println("Put: Obtained index:" + i);
for (Entry<K, V> e = table[i]; e != null; e = e.next) {
System.out.println("Put: Iteraing over table[" + i + "] elements");
Object k;
System.out.println("Put: Checking if hash & key are equal");
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
System.out.println("Put: Incrementing modCounter");
modCount++;
System.out.println("Put: Adding a new Entry[hash="
+ hash + ", key=" + key + ", value="
+ value + ", i=" + i + "]");
addEntry(hash, key, value, i);
return null;
}
然后使用以下输入进行测试,
MyHashMap p = new MyHashMap<>();
p.put(0, "Z");
p.put(1, "A");
p.put(17, "A");
猜猜输出是什么
Put: Table empty. Inflating table to threshold:16
Inflate: RoundUpPowerOf2 of size=16
Inflate: Setting Min of [capacity * loadFactor, MAXIMUM_CAPACITY + 1] as threshold
Inflate: Given values[capacity=16, loadfactor=0.75, MAXIMUM_CAPACITY=1073741824
Creating array of Entry[] with size:16
Put: Key not null:0
IndexFor: calculating index for [given hash=0, length=16]
Put: Obtained index:0
Put: Incrementing modCounter
Put: Adding a new Entry[hash=0, key=0, value=Z, i=0]
Put: Key not null:1
IndexFor: calculating index for [given hash=1, length=16]
Put: Obtained index:1
Put: Incrementing modCounter
Put: Adding a new Entry[hash=1, key=1, value=A, i=1]
Put: Key not null:16
IndexFor: calculating index for [given hash=16, length=16]
Put: Obtained index:0
Put: Iteraing over table[0] elements
Put: Incrementing modCounter
Put: Adding a new Entry[hash=16, key=17, value=A, i=0]
因此,如您所见,两个条目存储在同一个索引中。很高兴看到这样的行为。好奇地试图得到这个答案。