uladzimir
uladzimir

Reputation: 5689

Using custom classes as keys in map

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

Answers (2)

Willem
Willem

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

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

This depends on the kind of your map:

  • Keys of HashMap must provide hashCode and equals
  • Keys of 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

Related Questions