问题描述
我只想使用Collections.sort或Arrays.sort按x先排序一个点列表(类Point),然后再按y。
I just want to use Collections.sort or Arrays.sort to sort a list of points (class Point) by x first and then by y.
一个类Ponto实现Comparable像这样:
I have a class Ponto that implements Comparable like this:
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排序。
but now I want to sort by y too after x.
我如何通过修改上面的代码?或者是一个更好和干净的方式做到这一点?
我也使用把这段代码传递给C ++,其中我创建了一个结构,称为Point与一个等效的可比较的方法。
How can I do that by modifying the above code? Or is that a better and "clean" way to do this?I also use to pass this code to C++, in which I've created a structure called Point with a equivalent comparable method.
推荐答案
this.y
和的相同比较替换返回0
obj.y
。Replace return 0
by the same comparison algo on this.y
and obj.y
.
顺便说一下,在这里不需要重新分配 tmp
优化的图片可以是:
By the way, reassigning to tmp
is unnecessary here. The optimized picture can look like:
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;
}
}
这篇关于如何排序数组或ArrayList< Point> ASC先用x然后再用y?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!