Java - compareTo and operators

If I have a Person class that implements Comparable (e.g. compares personA.height with personB.height ), can I use

  personA < personB 

as a substitute for

  personA.compareTo(personB) == -1? 

Are there any problems with this or do I need to overload the operators?

+8
java operators comparable compareto
source share
6 answers

There is no operator overload in Java. You probably came from C ++ background.

You must use the compareTo method.

+6
source share

No, you cannot use personA < personB as a replacement. And you cannot overload operators in Java.

In addition, I recommend changing

 personA.compareTo(personB) == -1 

to

 personA.compareTo(personB) < 0 

You now probably have your class working. However, the compareTo() contract is that it returns a negative value if personA less than personB . This negative value should not be -1, and your code may break if it is used with another class. It can also break if someone changes your compareTo() class to another, but still compatible implementation.

+14
source share

It is impossible, no; and Java does not support operator overloading (besides built-in overloads).

By the way, instead of writing == -1 you should write < 0 . compareTo just needs to return a negative / zero / positive value, not specifically -1/0/1.

+5
source share

There is no operator 1 overload in Java, so yes, there is a problem: this is not possible.


1 There are, of course, several overloads: the + operator works with integer types, floating-point types, and String s. But you cannot define your own.

+1
source share

No, "<" will not compile when applied to objects. Also, be careful with your test:

 personA.compareTo(personB)==-1 

The docs API simply says compareTo () returns a negative integer when the object is less than the specified object, which will not necessarily be -1. Use

 personA.compareTo(personB) < 0 

instead.

+1
source share

Impossibly, java does not give you operator overloading.
But more OO options is to add a method inside a person

 public boolean isTallerThan(Person anotherPerson){ return this.compareTo(anotherPerson) > 0; } 

so instead of writing

 if(personA.compareTo(personB) > 0){ } 

You can write

 if(personA.isTallerThan(personB)){ } 

IMHO is more readable because it hides the details and is expressed in the domain language, and not in java-specific.

+1
source share

All Articles