How does a Java HashMap handle different objects with the same hash code?

前端 未结 14 1527
余生分开走
余生分开走 2020-11-22 02:27

As per my understanding I think:

  1. It is perfectly legal for two objects to have the same hashcode.
  2. If two objects are equal (using the equals() method)
14条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 03:30

    You can find excellent information at http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html

    To Summarize:

    HashMap works on the principle of hashing

    put(key, value): HashMap stores both key and value object as Map.Entry. Hashmap applies hashcode(key) to get the bucket. if there is collision ,HashMap uses LinkedList to store object.

    get(key): HashMap uses Key Object's hashcode to find out bucket location and then call keys.equals() method to identify correct node in LinkedList and return associated value object for that key in Java HashMap.

提交回复
热议问题