问题
I've been trying to learn the comparable class for sometime now, I know the correct syntax and the how it is used in most cases. Such as:
int result = ObjectA.compareTo(ObjectB);
would return a value of 0 if both object is the same; a negative value if object A is less then object B ,or a positive value if A is greater then B.
However when I go to actually write a program that uses the compareTo method, the compiler is saying that it can not find the compareTo method.
my question is: Do I have to directly inherit from the Comparable class in order to use the compareTo method? only reason I'm asking is because you do not have to explicitly inherit methods like toString or equals...because everything inherit from object. Where does CompareTo fall under?
回答1:
You need to implement the Comparable
interface:
public class MyClass implements Comparable<MyClass>
and then declare the compareTo()
method:
public int compareTo(MyClass myClass){
//compare and return result
}
回答2:
Comparable is an interface, not a class. So you would implement the interface, not subclass the class. Additionally, implementing the interface means implementing the compareTo
method yourself in your implementing class.
回答3:
- First, it will only work in instances. Don't know if your compare is comparing objects or the classes itself because of your naming. I will assume you are using objects :)
- The class you want to compare using
#compareTo
MUST implementComparable
. Another way to achieve this without having to implementComparable
is providing your sort method aComparator
expecting your class.
回答4:
Comparable
is an interface so you do not "inherit" it (extends
), but implement it (implements
).
You can write your own compareTo
method in your class without specifying the Comparable
interface, but then the methods in the API won't know if your object meets the contract that Comparable
enforces. So, you won't be able to use methods like Arrays.sort()
and the like that expect to work with objects that do enforce Comparable
.
回答5:
If you want the objects of your class A
compared, possibly because you like to sort a list of those objects, you need to make the class A
implement Comparable
interface.
Once the class A
implements Comparable
it must implement and define the behavior of compareTo
, which is essentially how you want two objects of class A
be compared.
It it this method where you can decide which fields of the class A
take part in evaluating the lesser- or greaterness of an object.
来源:https://stackoverflow.com/questions/15421289/comparable-class