In Java, what interface(class) should a class implement(extend) in order to allow two instances of the class to be comparable through relational operators like "<" or ">="?
Asked
Active
Viewed 743 times
2 Answers
11
This is not possible in Java.
If you want objects of your class to be comparable, implement Comparable
.

Björn Pollex
- 75,346
- 28
- 201
- 283
-
Im just curious, but could he override the compare to with what ever factors he wants to compare them, and do something like obj1.compareTo(obj2) > 0 which means (obj1 > obj2)??? – RMT Jun 21 '11 at 13:22
-
1Thanks. I was just trying to do something more readable than `compareTo()` – Tiago Veloso Jun 21 '11 at 13:22
-
@RMT: That is exactly what implementing `Comparable` does. – Björn Pollex Jun 21 '11 at 13:23
-
I think they should add this possibility in the future. – Tiago Veloso Jun 21 '11 at 13:32
4
Java does not support operator overloading, so you're out of luck. Implementing java.lang.Comparable
or providing a java.util.Comparator
is what you're supposed to do.

Christian Schwartz
- 355
- 2
- 5