我只想使用 Collections.sort 或 Arrays.sort 先按 x 然后按 y 对点列表(Point 类)进行排序。
我有一个像这样实现 Comparable 的 Ponto 类:
public int compareTo(Ponto obj) {
Ponto tmp = obj;
if (this.x < tmp.x) {
return -1;
} else if (this.x > tmp.x) {
return 1;
}
return 0;
}
但现在我也想在 x 之后按 y 排序。
如何通过修改上面的代码来做到这一点?或者这是一种更好、更“干净”的方法吗? 我还使用将此代码传递给 C++,在 C++ 中我使用等效的可比较方法创建了一个名为 Point 的结构。
最佳答案
用 this.y
和 obj.y
上的相同比较算法替换 return 0
。
顺便说一句,这里不需要重新分配给tmp
。优化后的图片看起来像:
public int compareTo(Ponto other) {
if (this.x == other.x) {
return (this.y < other.y) ? -1 : ((this.y == other.y) ? 0 : 1);
} else {
return (this.x < other.x) ? -1 : 1;
}
}
关于java - 如何先按 x 然后按 y 对数组或 ArrayList<Point> ASC 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2741846/