Setting own class as key in java Hashmap

后端 未结 8 1967
萌比男神i
萌比男神i 2020-12-09 10:24

I have a class which I want to set up as keys in HashMap. I already have implemented the compareTo method for that class. But still when I do:

map.put(new MyKey(d         


        
8条回答
  •  悲&欢浪女
    2020-12-09 11:19

    When using Collections that rely on hashing like Map and Set you have to implement the equals() and hashCode() to guarantee correct functionality. If you don't a new myKey will always be different from the key stored in the map because it uses the default implementations of equals() and hashCode().

提交回复
热议问题