-2
String abc = "abc";
String abc2 = new String("abc");
System.out.println(abc == abc2); //false
Map<String, Integer> map = new HashMap<String, Integer>();
map.put(abc, 2);
System.out.println("map.get(abc)" + map.get("abc")); //2
map.put(abc2, 1234);
System.out.println("map.get(abc)" + map.get("abc")); //1234

If abc and abc2 are not equal then why Hashmap is overriding values?

carlspring
  • 31,231
  • 29
  • 115
  • 197
Manohar V
  • 1
  • 1
  • 2
    `abc` and `abc2` are equal! You are not checking for equallity on line 3 but if they are the same object. `abc.equals(abc2)` is how you check if they are equal. – OH GOD SPIDERS Oct 04 '17 at 16:35

3 Answers3

1

A Map is a structure that will store (key/value)(called Entry) elements and where keys will be unique

Since abc.equals(abc2) is true, abc2 will replace abc


To check equality you need to use .equals() and not == which is for reference

abc and abc2 are not the same object (== is false) and they represent the SAME string (.equals() is true, and so only one can be in the Map)

String abc = "abc";
String abc2 = new String("abc");
System.out.println(abc.equals(abc2)); //line 3 :  true
map.put(abc, 2);      
map.put(abc2, 1234);                  //because of line 3 it will override precedent input (line 4)
System.out.println(map.toString());   //[abc=1234]
azro
  • 53,056
  • 7
  • 34
  • 70
0

Since abc.equals(abc2) is always true for those values.

While abc == abc2 is not necessarily true for their references.


And that being said you shall be able to understand

map.put(abc, 2);
map.put(abc2, 1234); // overrides the previous value with the same key
Naman
  • 27,789
  • 26
  • 218
  • 353
-1

String generates the hash based on the value, the key will be the same for both objects so both objects are pointing to the same key (hash) & abc.equals(abc2 ) is true So both objects are pointing to the same entry.

String abc = "abc"; String abc2 = new String("abc");

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}
Manohar V
  • 1
  • 1
  • Thats not even the correct answer. What matters is that both Strings are equal! HashMap is perfectly capable of handling multiple unequal objects with the same hashcode: https://stackoverflow.com/questions/6493605/how-does-a-java-hashmap-handle-different-objects-with-the-same-hash-code – OH GOD SPIDERS Oct 04 '17 at 16:56
  • I forgot to add abc.equals(abc2 ) I think now it is ok – Manohar V Oct 04 '17 at 17:08