Reputation: 5689
What methods, if any, does a custom class need to implement in order to be used as a key in a Map
?
Upvotes: 1
Views: 711
Reputation: 376
If you want to use a TreeMap your class will have to implement Comparable. If you are using a HashMap you will need a good hash function.
Upvotes: 1
Reputation: 726569
This depends on the kind of your map:
HashMap
must provide hashCode
and equals
TreeMap
need to provide compareTo
by implementing Comparable<T>
unless the map is constructed with a Comparator
, in which case there are no restrictions on the key itself.Upvotes: 5