Question

I'm sorry if this question was already asked, but i don't fine an answer to my question. I'm working on HashMap i put two values (7,"value test 1") (7,"value test 2) According to the specification java API HashMap put the first values is replaced by the second .

My question is when comes the resolution of collision ? why my second value is not store in linkedList or store in another place in the hashMap ? Is it due to the equals or hascode method ??

Best Regards

Was it helpful?

Solution

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?

OTHER TIPS

Collision handling takes place if two different keys resolve to the same bucket in the hashmap. In that case the second entry would be put into the linked list.

In your case you replace the entry for the same key (7) and thus there is no collision.

If you need a map that contains multiple values per key either use a Map<key, Set<value>> (you can also use a List etc. instead of a Set) and handle adding/removing to that set yourself or use Apache Commons' MultiMap or Google Guava's Multimap, e.g. HashMultimap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top