Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when to implement comparable and when to implement equals in Java

In Java, when should I implement Comparable<Something> versus implementing the equals method? I understand every time I implement equals I also have to implement hash code.

EDIT

Based on answers I am getting below:

Is it safe to say that if I implement Comparable then I don't need to implement equals and hashCode? As in: whatever I can accomplish with equal is already included in compareTo? For an example, I want to be able to compare two BSTs for equality. Implementing a hashCode for that seems daunting; so would comparable be sufficient?

like image 976
Katedral Pillon Avatar asked Apr 09 '26 08:04

Katedral Pillon


1 Answers

If you only ever need to compare them for equality (or put them in a HashMap or HashSet which is effectively the same) you only need to implement equals and hashcode.

If your objects have an implicit order and you indend to sort them (or put them in a TreeMap or TreeSet which is effectively sorting) then you must implement Comparable or provide a Comparator.

like image 93
OldCurmudgeon Avatar answered Apr 10 '26 22:04

OldCurmudgeon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!