lowLatency
lowLatency

Reputation: 5654

Size of HashMap when using same literal/string Object as Key?

Please let me know if my understanding is correct:
Size of HashMap is 2 here because String equals(compare the state/content and not the location on heap) method comes into picture when we put the keys in the below map

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

Upvotes: 1

Views: 1266

Answers (4)

arjacsoh
arjacsoh

Reputation: 9232

Because Map uses the equals() method to check the existence of a key in the Map. It checks if the Objects-keys are meaningfully equal. In String class the equals() method is overrided by the API and the comparison "one" to new String("one") returns true. After equals() method returning true, the new element replaces the old, since duplicate keys are not allowed in Map. Therefore you have only one element with key "one"

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

Yes.

source code is the proof.

Since you are using Strings as keys , key.equals(k) is true for the case "one" as key.

     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     }

Here is the essential condition check:

if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {

Upvotes: 5

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

Yes. and You can't have duplicate keys in Map.Both "one" and new String("one") has same state("one".equals(new String("one"))).So in this case first two has same key.

Upvotes: 1

wchargin
wchargin

Reputation: 16037

Yes, that's correct.

For reference you can simply run hashMap.size().

Upvotes: 1

Related Questions