Setting own class as key in java Hashmap

后端 未结 8 1945
萌比男神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

    You should implement equals() and hashCode(). Your class should also be immutable. If it is mutable, it's hash code can change after adding it to map. Then the map can have problems finding it.

提交回复
热议问题