所以,我只是试图测试如何在我自己的类型上使用compareTo
方法,并且即使是最简单的情况也无法使它工作。我的代码(自解释)如下(它在用户定义的类型TestType
下创建了一个15 - > 1的“数字”数组。我希望它能够“自然地”排序。
public class TestType implements Comparable<TestType> {
public int n;
TestType(int _n) {
n = _n;
}
@Override
public int compareTo(TestType otherType) {
return this.n < otherType.n ? -1 : (this.n > otherType.n ? 1 : 0);
}
public static void main(String[] args){
TestType[] a = new TestType[15];
for(int i = 0; i < 15; i++){
a[i] = new TestType(15 - i);
System.out.println(a[i].n);
}
a.sort();
}
}
如果你能看出它为什么不起作用,请告诉我:)。
答案 0 :(得分:6)
我认为你应该写Arrays.sort(a);
。
答案 1 :(得分:0)
您是否尝试过Arrays.sort(a)
而不是a.sort()
?