Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - compareTo and operators

If I have a class Person that implements Comparable (compares personA.height to personB.height, for example), is it possible to use

    personA < personB

as a substitute for

    personA.compareTo(personB) == -1? 

Are there any issues in doing this or do I need to overload operators?

like image 601
Chet Avatar asked Jan 20 '12 18:01

Chet


Video Answer


2 Answers

No, it isn't possible to use personA < personB as a substitute. And you can't overload operators in Java.

Also, I'd recommend changing

personA.compareTo(personB) == -1

to

personA.compareTo(personB) < 0

What you have now probably works for your class. However, the contract on compareTo() is that it returns a negative value when personA is less than personB. That negative value doesn't have to be -1, and your code might break if used with a different class. It could also break if someone were to change your class's compareTo() method to a different -- but still compliant -- implementation.

like image 73
NPE Avatar answered Oct 22 '22 12:10

NPE


It is not posible, java does not give you operator overload.
But a more OO option is to add a method inside 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 it is more readable because it hides details and it is expressed in domain language rather than java specifics.

like image 22
Pablo Grisafi Avatar answered Oct 22 '22 10:10

Pablo Grisafi