Java - compareTo and operators
Asked Answered
N

6

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?

Noisette answered 20/1, 2012 at 18:25 Comment(0)
L
6

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

You have to use the compareTo method.

Lexicographer answered 20/1, 2012 at 18:27 Comment(0)
C
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.

Cullis answered 20/1, 2012 at 18:26 Comment(0)
L
6

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

You have to use the compareTo method.

Lexicographer answered 20/1, 2012 at 18:27 Comment(0)
D
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.

Despotic answered 20/1, 2012 at 18:28 Comment(0)
B
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.

Benniebenning answered 20/1, 2012 at 18:48 Comment(0)
F
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.

Fellatio answered 20/1, 2012 at 18:27 Comment(0)
N
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.

Nickens answered 20/1, 2012 at 18:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.