ava如何对ArrayList中对象按照该对象某属性排序
(从小到大)
两种方法:
[tr=none]
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
KNNNode 的 distance 属性对 ArrayList 进行排序以下是两种实现方式,分别从 从小到大 和 从大到小 排序的角度进行说明,并解决您提到的 Comparison method violates its general contract! 问题。
Comparator通过 Collections.sort 方法结合匿名内部类实现排序。以下是具体代码:
// 定义 Comparator 实现从小到大排序
Comparator<KNNNode> comparator = new Comparator<KNNNode>() {
@Override
public int compare(KNNNode o1, KNNNode o2) {
// 确保处理相等情况时返回 0
if (o1.getDistance() < o2.getDistance()) {
return -1;
} else if (o1.getDistance() > o2.getDistance()) {
return 1;
} else {
return 0;
}
}
};
// 调用排序方法
List<KNNNode> nodeList = new ArrayList<>();
// 填充 nodeList
nodeList.add(new KNNNode(1, 3.5, "seq1"));
nodeList.add(new KNNNode(2, 2.1, "seq2"));
nodeList.add(new KNNNode(3, 4.8, "seq3"));
Collections.sort(nodeList, comparator);
从大到小排序 的实现只需调整比较逻辑:
Comparator<KNNNode> comparatorDesc = new Comparator<KNNNode>() {
@Override
public int compare(KNNNode o1, KNNNode o2) {
if (o1.getDistance() > o2.getDistance()) {
return -1;
} else if (o1.getDistance() < o2.getDistance()) {
return 1;
} else {
return 0;
}
}
};
Collections.sort(nodeList, comparatorDesc);
Comparator 类通过定义一个独立的类实现 Comparator 接口,便于复用和维护。以下是具体代码:
// 定义独立的 Comparator 类
class SortByDistanceAsc implements Comparator<KNNNode> {
@Override
public int compare(KNNNode o1, KNNNode o2) {
if (o1.getDistance() < o2.getDistance()) {
return -1;
} else if (o1.getDistance() > o2.getDistance()) {
return 1;
} else {
return 0;
}
}
}
class SortByDistanceDesc implements Comparator<KNNNode> {
@Override
public int compare(KNNNode o1, KNNNode o2) {
if (o1.getDistance() > o2.getDistance()) {
return -1;
} else if (o1.getDistance() < o2.getDistance()) {
return 1;
} else {
return 0;
}
}
}
// 调用排序方法
List<KNNNode> nodeList = new ArrayList<>();
nodeList.add(new KNNNode(1, 3.5, "seq1"));
nodeList.add(new KNNNode(2, 2.1, "seq2"));
nodeList.add(new KNNNode(3, 4.8, "seq3"));
// 从小到大排序
Collections.sort(nodeList, new SortByDistanceAsc());
// 从大到小排序
Collections.sort(nodeList, new SortByDistanceDesc());
Comparison method violates its general contract! 的解决方案该异常通常是由于 compare 方法未正确处理相等情况(即 o1.getDistance() == o2.getDistance())导致的。根据 Java 的 Comparator 规范,compare 方法必须满足以下条件:
compare(x, x) 必须返回 0。compare(x, y) 和 compare(y, x) 的结果必须互为相反数。compare(x, y) > 0 且 compare(y, z) > 0,则 compare(x, z) > 0。因此,在实现 compare 方法时,必须确保在 o1.getDistance() == o2.getDistance() 时返回 0,避免直接返回非零值。
o1.getDistance() < o2.getDistance() 返回 -1,o1.getDistance() > o2.getDistance() 返回 1,相等时返回 0。o1.getDistance() > o2.getDistance() 返回 -1,o1.getDistance() < o2.getDistance() 返回 1,相等时返回 0。compare 方法严格遵守 Comparator 的规范,避免因相等情况未处理而导致运行时异常。希望以上内容能够帮助您高效实现 ArrayList 中对象的排序!