Collision resolution in Java HashMap

前端 未结 9 1946
半阙折子戏
半阙折子戏 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:26

    First of all, you have got the concept of hashing a little wrong and it had been rectified by Mr. Sanjay.

    And yes, Java indeed implement a collision resolution technique. When two keys get hashed to a same value (as the internal array used is finite in size and at some point the hashcode() method will return same hash value for two different keys) at this time, a linked list is formed at the bucket location where all the informations are entered as an Map.Entry object that contains a key-value pair. Accessing an object via a key will at worst require O(n) if the entry in present in such a lists. Comparison between the key you passed with each key in such list will be done by the equals() method.

    Although, from Java 8 , the linked lists are replaced with trees (O(log n))

提交回复
热议问题