如何排序数组或ArrayList< Point> ASC先用x然后再用y? [英] How to sort an array or ArrayList<Point> ASC first by x and then by y?

查看:137
本文介绍了如何排序数组或ArrayList< Point> ASC先用x然后再用y?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想使用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&lt; Point&gt; ASC先用x然后再用y?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆