How to make HashMap work properly with custom key type?

后端 未结 3 2118
礼貌的吻别
礼貌的吻别 2020-12-11 17:10

I think my question is quite simple, however I couldn\'t find the solution so I decided to ask here. What i need is to make a HashMap with a custom Key type lik

相关标签:
3条回答
  • 2020-12-11 17:21

    You must implement properly equals and hashCode on the Pair class.

    The HashMap uses these methods to differentiate and hash the key class.

    0 讨论(0)
  • 2020-12-11 17:33

    Your Pair class need to implement hashCode() and equals() according to the contract specified in the Javadoc for Object.

    0 讨论(0)
  • 2020-12-11 17:38

    You need to override equals in the class Pair. The implementation of this method defines how two objects of Pair are considered equal.

    And whenever you override equals you must always override hashcode.

    Here is what can go wrong when you override equals but not hashcode (from Effective Java, Second Ed.):

    Two distinct instances may be logically equal according to a class’s equals method, but to Object’s hashCode method, they’re just two objects with nothing much in common. Therefore Object’s hashCode method returns two seemingly random numbers instead of two equal numbers as required by the contract.

    Because the hashcodes for two logically equal instances become unequal, if you try to search for one while another is in the collection, you will end up looking in the wrong hash bucket which results in null.

    There is a set of rules that implementation of equals must conform to. Another set of rules for overriding hashcode.

    0 讨论(0)
提交回复
热议问题