I just want to be sure that my code is safe using Integer
objects as keys. Here's a short example:
Integer int1 = new Integer(1337);
Integer int2 = new Integer(1337);
if (int1 == int2) {
System.out.println("true");
} else {
System.out.println("false");
}
if (int1.equals(int2)) {
System.out.println("true");
} else {
System.out.println("false");
}
Map<Integer, Object> map = new HashMap<Integer, Object>();
map.put(int1, null);
map.put(int2, null);
System.out.println(map.size());
The code will output
false
true
1
That's what I was expecting, the references differ but they equal each other. Now I'm interested in the Map's behavior.
- Is it guaranteed that Collections like Map or Set will compare the keys by their content and not their reference?
- Or depends it on the actual implementation, like
HashMap
?