dganesh2002 :
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");
}
michalk :
Integer
s are object types so for comparing them you should use Integer::equals
. For Integer
s 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.
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=327735&siteId=1