10

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?

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
Chet
  • 1,209
  • 1
  • 11
  • 29

6 Answers6

15

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
6

There is no operator overloading in Java. You probably come from a C++ background.

You have to use the compareTo method.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
5

It's not possible, no; and Java doesn't support operator overloading (besides the built-in overloads).

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

ruakh
  • 175,680
  • 26
  • 273
  • 307
2

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.

Pablo Grisafi
  • 5,039
  • 1
  • 19
  • 29
1

Java doesn't have operator overloading1, so, yes, there's an issue: this is not possible.


1 There are, of course, a few overloadings built in: the + operator works on integral types, floating-point types, and on Strings. But you can't define your own.

Leponzo
  • 624
  • 1
  • 8
  • 20
Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
1

No, the "<" won't compile when applied to objects. Also, be careful of your test:

personA.compareTo(personB)==-1

The API docs merely say that compareTo() returns a negative integer when the object is less than the specified object, which won't necessarily be -1. Use

personA.compareTo(personB) < 0

instead.

Stevens Miller
  • 1,387
  • 8
  • 25