这是我的类(class):
public static class __9_7_Person implements Comparator<__9_7_Person> {
private int height;
private int weight;
public __9_7_Person(int height, int weight) {
this.height = height;
this.weight = weight;
}
public int compare(__9_7_Person p1, __9_7_Person p2) {
if (p1.height != p2.height) {
return p1.height - p2.height;
}
else {
return p1.weight - p2.weight;
}
}
}
然后我创建了一个这样的数组:
__9_7_Person p[] = {new __9_7_Person(60, 100),
new __9_7_Person(70, 150),
new __9_7_Person(56, 90),
new __9_7_Person(75, 190),
new __9_7_Person(60, 95),
new __9_7_Person(68, 110),
};
但是当我调用 Arrays.sort(p) 时出现异常:“线程“主”java.lang.ClassCastException 中的异常:ch_9$__9_7_Person 无法转换为 java.lang.Comparable”
最佳答案
您实现的是 Comparator,而不是 Comparable。您应该实现 Comparable 而不是 Comparator。
如前所述in the docs :
All elements in the array must implement the Comparable interface.
如果您希望能够对同一类进行不同的排序,则比较器很有用。在这种情况下,不能使用 Comparable
关于java - 实现了比较但在调用 Arrays.sort 时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11385655/