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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With