Java - HashMap confusion about collision handling and the get() method

前端 未结 5 1849
说谎
说谎 2021-01-13 15:28

I\'m using a HashMap and I haven\'t been able to get a straight answer on how the get() method works in the case of collisions.

Let\'s say

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-13 15:43

    Are they overwritten so that only the last object placed in that key exists there anymore?

    Yes, assuming you're putting multiple values with the same key (according to Object.equals, not Object.hashCode.) That's specified in the Map.put javadoc:

    If the map previously contained a mapping for the key, the old value is replaced by the specified value.

    If you want to map a key to multiple values, you're probably better off using something like Guava's ListMultimap, ArrayListMultimap in specific, which maps keys to lists of values. (Disclosure: I contribute to Guava.) If you can't tolerate a third-party library, then really you have to have a Map>, though that can get a bit unwieldy.

提交回复
热议问题