1

Why I'm getting only the message "a value is same" as an output ? Is it due to some auto-boxing ?

Code :

 Map<Character, Integer> pMap = new HashMap<>();
    Map<Character, Integer> sMap = new HashMap<>();
    char c = 'a';
    pMap.put(c, 10);
    sMap.put(c, 10);
    if (sMap.get(c) == pMap.get(c)) {
        System.out.println(c + " value is same");
    }
    char d = 'b';
    pMap.put(d, 10000);
    sMap.put(d, 10000);
    if (sMap.get(d) == pMap.get(d)) {
        System.out.println(d + " value is same");
    }
Anish B.
  • 9,111
  • 3
  • 21
  • 41
dganesh2002
  • 1,917
  • 1
  • 26
  • 29

1 Answers1

3

Integers are object types so for comparing them you should use Integer::equals. For Integers in range [-128 , 127] there is a special Integer pool. When you put your int values in the map, they are boxed to Integer - hence same values in your map, between [-128 , 127], will be references to same values in Integer pool. That is why == for [-128 , 127] values returns true. But generally you should use equals here or perform unboxing explicitly.

Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63