Search code examples
javaobjectcomparable

Java: Compare objects using >, < and ==


Is it possible to properly compare objects using the operators >, < and == in Java? I have implemented the Comparable interface in one of my objects.

It would save some time and be nice to write

if (obj1 < obj2) do sth

instead of

if (obj1.compareTo(obj2) < 0) do sth

Is that possible if I implement something else or does it generally not work like this?


Solution

  • In a word- no, it is not possible. Java does not support operator overloading, and the comparison operators (<, <=, > and <=) are reserved for primitive types only.