请让我知道我的理解是否正确:
HashMap 的大小在这里是 2,因为当我们将键放在下面的映射中时,String equals(比较状态/内容而不是堆上的位置)方法出现了
Map hashMap = new HashMap();
hashMap.put("one", "1");
hashMap.put(new String("one"), "2");
hashMap.put("two", "3");
System.out.println("Hash Map KeySet Size : " + hashMap.keySet().size());
最佳答案
是的。
因为您使用字符串作为键,key.equals(k)
对于 "one"
作为键的情况是 true
。
public V put(K key, V value) {
387 if (key == null)
388 return putForNullKey(value);
389 int hash = hash(key.hashCode());
390 int i = indexFor(hash, table.length);
391 for (Entry<K,V> e = table[i]; e != null; e = e.next) {
392 Object k;
393 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
394 V oldValue = e.value;
395 e.value = value;
396 e.recordAccess(this);
397 return oldValue;
398 }
399 }
400
401 modCount++;
402 addEntry(hash, key, value, i);
403 return null;
404 }
这是基本条件检查:
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
关于java - 使用相同的文字/字符串对象作为键时 HashMap 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18711223/