Setting own class as key in java Hashmap

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

    As of java8 you should also implement Comparable (adding compareTo) because if the number of hash clashes exceeds 11, HashMap stores the entries in a binary tree. If you don't, performance suffers

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-09 11:18

    Do you have the hashCode() defined? compareTo is needed for sorting.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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().

    0 讨论(0)
  • 2020-12-09 11:20

    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.

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