This interface imposes a total ordering on the objects of each class
that implements it. This ordering is referred to as the class's
natural ordering, and the class's compareTo method is referred to as
its natural comparison method.
{a2}方法:
Compares this object with the specified object for order. Returns a
negative integer, zero, or a positive integer as this object is less
than, equal to, or greater than the specified object.
以下是一个示例:
public class MyComparable implements Comparable< MyComparable >{
private int value;
@Override
public int compareTo( MyComparable other ) {
return this.value - other.value;
}
public MyComparable( int i ) {
value = i;
}
public static void main( String[] args ) {
MyComparable _12 = new MyComparable( 12 );
MyComparable _42 = new MyComparable( 42 );
MyComparable _12bis = new MyComparable( 12 );
System.out.println( _12.compareTo( _42 ));
System.out.println( _42.compareTo( _12 ));
System.out.println( _12.compareTo( _12bis ));
}
}
# 1 楼答案
首先,阅读documentation
{a2}方法:
以下是一个示例:
它输出:
# 2 楼答案
Comparable是一个接口,因此它不包含任何逻辑。具有
implement Comparable
的具体类必须实现.compareTo()
方法,如here所述实现此接口意味着您希望该类能够将自身与另一个实例进行比较,并返回一个数值,表示该类应被视为比传入的实例“大”还是“小”。这通常用于集合中的排序
例如: