问题
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?
回答1:
There is no operator overloading in Java. You probably come from a C++ background.
You have to use the compareTo
method.
回答2:
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.
回答3:
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.
回答4:
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.
回答5:
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.
回答6:
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 String
s. But you can't define your own.
来源:https://stackoverflow.com/questions/8946071/java-compareto-and-operators