Описание тега comparable
In Java, this interface is implemented by a class to indicate that it can be compared to another object and therefore ordered.
In Java, this interface is implemented by a class to indicate that it can be compared to another object and therefore ordered. The interface defines one method: compareTo()
. Classes can either implement it as a raw type, as with older versions of Java:
public class MyClass implements Comparable
{
public int compareTo(Object other)
{
MyClass toCompare = (MyClass) other;
//...
}
}
Or, as of Java 1.5, a class can use generics:
public class MyClass implements Comparable<MyClass>
{
public int compareTo(MyClass other)
{
//...
}
}
The general contract of compareTo()
is:
- If
this
is less than the parameter, it returns a value less than zero. - If
this
is greater than the parameter, it returns a value greater than zero. - Otherwise, if
this
is equal to the parameter, returns zero.
The actual value of compareTo()
is irrelevant; only the sign of the return value matters.
Javadoc for java.lang.Comparable