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

前端 未结 5 1852
说谎
说谎 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:51

    Cite: "Let's say n > 1 objects get placed in the same key. Are they stored in a linked list? Are they overwritten so that only the last object placed in that key exists there anymore? Are they using some other collision method?"

    Yes, if the hashmap contained something under this key, it will override it.

    You can implement your own class to handle that or more simple use a HashMap> in where K is your Key Object and V the object value. Have in mind that with last solution when you do a map.get(K) will retrieve a List or the implementation that you choose (i.e: ArrayList) so all the methods of this implementation are available for you and perhaps fulfils your requirements. For example if you used Arraylist you have the size, trimToSize, removeRange, etc.

提交回复
热议问题