Setting own class as key in java Hashmap

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

    1) In general for collections, what you want to override is the equals() method (and also the hashcode() method) for your class. compareTo()/Comparable and Comparator are typically used for sorting and only take the place of using the equals() method for object equivalance in some cases - examples are implementers of SortedSet such as TreeSet.

    2) Please conform to Java naming standards in your code. Your class names should be capitalized... e.g new MyKey(dummyArguments). See http://www.oracle.com/technetwork/java/codeconventions-135099.html#367 (and http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) for more detail.

提交回复
热议问题