Collision resolution in Java HashMap

前端 未结 9 1948
半阙折子戏
半阙折子戏 2020-12-12 12:29

Java HashMap uses put method to insert the K/V pair in HashMap. Lets say I have used put method and now HashMap<

9条回答
  •  时光说笑
    2020-12-12 13:16

    Your case is not talking about collision resolution, it is simply replacement of older value with a new value for the same key because Java's HashMap can't contain duplicates (i.e., multiple values) for the same key.

    In your example, the value 17 will be simply replaced with 20 for the same key 10 inside the HashMap.

    If you are trying to put a different/new value for the same key, it is not the concept of collision resolution, rather it is simply replacing the old value with a new value for the same key. It is how HashMap has been designed and you can have a look at the below API (emphasis is mine) taken from here.

    public V put(K key, V value)

    Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.


    On the other hand, collision resolution techniques comes into play only when multiple keys end up with the same hashcode (i.e., they fall in the same bucket location) where an entry is already stored. HashMap handles the collision resolution by using the concept of chaining i.e., it stores the values in a linked list (or a balanced tree since Java8, depends on the number of entries).

提交回复
热议问题