使用相同的文字/字符串对象作为键时HashMap的大小?

时间:2013-09-10 05:21:19

标签: java string hashmap

如果我的理解是正确的,请告诉我:
这里HashMap的大小是2,因为当我们将键放在下面的地图中时,String等于(比较状态/内容而不是堆上的位置)方法进入图片

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());

4 个答案:

答案 0 :(得分:5)

source code is the proof.

由于您使用字符串作为键,因此案例key.equals(k)的{​​{1}}为true作为键。

"one"

这是基本条件检查:

     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     }

答案 1 :(得分:1)

是的,这是正确的。

作为参考,您只需运行hashMap.size()即可。

答案 2 :(得分:1)

是。并且您不能在Map中拥有重复的密钥。"one"new String("one")都具有相同的状态("one".equals(new String("one")))。因此,在这种情况下,前两个具有相同的密钥。

答案 3 :(得分:1)

由于Map使用equals()方法检查Map中是否存在密钥。它检查Objects-keys是否有意义相等。在String类中,equals()方法会覆盖API方法,而"one"new String("one")的比较将返回true。在equals()方法返回true后,新元素将替换旧元素,因为Map中不允许使用重复的键。因此,您只有一个键为“one”的元素