Reputation: 6086
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?
Upvotes: 2
Views: 143
Reputation: 312086
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.
Upvotes: 2
Reputation: 220
< > Operators are only usable on primitives - such as integers.
Upvotes: 0
Reputation: 692081
No, it's not possible. These operators only work on primitive types.
Upvotes: 1
Reputation: 22015
No, this is not possible. Java does not support operator overloading.
You might want to check Groovy, which is a Java like language that runs on the JVM and does support operator overloading.
Upvotes: 5