This has nothing to do with hash collision. Hash collisions (ie., keys with the same hashcode()
) are handled correctly by the HashMap. In your example, both keys are equal (ie., 7.equals(7) == true
), so the old value is replaced.
In the following example
Map<Integer, String> map = new HashMap<>();
map.put(7, "value 1");
map.put(7, "value 2");
System.out.println(map.get(7));
what would you expect in the last line to happen?
Maybe you are looking for a multimap?