0

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

asko
  • 45
  • 4
  • If you want to store multiple values for a same key, you can use MultiMap from apache collections. https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.1/org/apache/commons/collections/MultiMap.html – gaganbm Apr 23 '14 at 12:21
  • Just in case you didnt know, `Map#put` returns the old value in such a case so you can do whatever you want with it. – A4L Apr 23 '14 at 12:23

2 Answers2

3

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?

Community
  • 1
  • 1
Cephalopod
  • 14,632
  • 7
  • 51
  • 70
  • that's the strutures i was looking for !! Maybe a silly question lol .. i was expected that the call to get method ont this index return an object LinkedList or something like that ... Why Java dev have choosen this implementation ? – asko Apr 23 '14 at 12:36
  • Because that's what a Map does. It maps one integer to one string (in this case). Cf. http://en.wikipedia.org/wiki/Map_%28mathematics%29 and http://en.wikipedia.org/wiki/Map_%28computer_science%29. Why the JDK doesn't ship a MultiMap, too, is a good question, though. – Cephalopod Apr 23 '14 at 12:42
0

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.

Thomas
  • 87,414
  • 12
  • 119
  • 157
  • I just realized what you were saying... too early in the morning for SO... Retracting my -1 and my comment. – jgitter Apr 23 '14 at 12:28