如何先按x然后按y对数组或ArrayList <Point> ASC进行排序?

nev*_*ind 1 c++ java sorting comparison

我只想使用Collections.sort或Arrays.sort先按x排序点(Point类),然后按y排序.

我有一个类Ponto实现Comparable像这样:

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;
    }
Run Code Online (Sandbox Code Playgroud)

但现在我想在x之后按y排序.

我怎么能通过修改上面的代码来做到这一点?或者这是一种更好,更"干净"的方法吗?我还使用这个代码传递给C++,其中我用类似的可比方法创建了一个名为Point的结构.

Bal*_*usC 6

替换return 0为相同的比较算法this.yobj.y.

顺便说一句,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;
    }
}
Run Code Online (Sandbox Code Playgroud)