2

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?

1
  • No Java does not support operator overloading (except for Strings that you can concatenate with +). Commented Dec 10, 2014 at 11:21

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@CGFoX You can also check Scala which runs on the JVM and support operator overloading (you could even mix Scala and Java code).
2

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.

Comments

1

No, it's not possible. These operators only work on primitive types.

Comments

0

< > Operators are only usable on primitives - such as integers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.