Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java ArrayList首先按距离排序,然后按类型排序_Java_Arraylist - Fatal编程技术网

Java ArrayList首先按距离排序,然后按类型排序

Java ArrayList首先按距离排序,然后按类型排序,java,arraylist,Java,Arraylist,我有一个ArrayList,我试图根据两个条件对其进行排序。首先按距离,然后按类型d_距离是一个双精度值,对于每个对象都是唯一的。没有两个d_距离可以相等type是1-6中的整数,两个对象可以是同一类型。以下是我的实现: Collections.sort(list, new Comparator<Abc>() { @Override public int compare(Abc lhs, Abc rhs) {

我有一个
ArrayList
,我试图根据两个条件对其进行排序。首先按距离,然后按类型
d_距离
是一个双精度值,对于每个对象都是唯一的。没有两个
d_距离可以相等
type
1-6
中的整数,两个对象可以是同一类型。以下是我的实现:

Collections.sort(list, new Comparator<Abc>() {

            @Override
            public int compare(Abc lhs, Abc rhs) {

                if (lhs.d_distance > rhs.d_distance)
                    return 1;

                if (lhs.d_distance < rhs.d_distance){

                    if (lhs.type > rhs.type)
                        return 1;

                    if (lhs.type < rhs.type)
                        return -1;

                    return -1
                }
                return 0;
            }
        });
Collections.sort(列表,新比较器(){
@凌驾
公共整数比较(Abc lhs、Abc rhs){
如果(左S.d_距离>右S.d_距离)
返回1;
if(左S.d_距离<右S.d_距离){
如果(左侧类型>右侧类型)
返回1;
if(左S型<右S型)
返回-1;
返回-1
}
返回0;
}
});

最简单的实现

            @Override
            public int compare(Abc lhs, Abc rhs) {

                if (lhs.d_distance != rhs.d_distance)
                    return lhs.d_distance < rhs.d_distance ? -1 : 1;

                return lhs.type - rhs.type;
            }

使用JDK实用程序方法和帮助比较:

Collections.sort(list, new Comparator<Abc>() {
        @Override
        public int compare(Abc lhs, Abc rhs) {
            int c = Double.compare(lhs.d_distance, rhs.d_distance);
            return c == 0 ? Integer.compare(lhs.type, rhs.type) : c;
        }
    });
Collections.sort(列表,新比较器(){
@凌驾
公共整数比较(Abc lhs、Abc rhs){
int c=双比较(左S.d_距离,右S.d_距离);
返回c==0?整数。比较(lhs.type,rhs.type):c;
}
});
但如果距离真的是唯一的,那么编码它们是否相等是没有价值的,所以:

Collections.sort(list, new Comparator<Abc>() {
        @Override
        public int compare(Abc lhs, Abc rhs) {
            return Double.compare(lhs.d_distance, rhs.d_distance);
        }
    });
Collections.sort(列表,新比较器(){
@凌驾
公共整数比较(Abc lhs、Abc rhs){
返回双比较(左S.d_距离,右S.d_距离);
}
});

你的问题是什么?@barq我的实现不起作用这不是问题。准确解释什么不起作用。输出错误?例外情况?错误?@Takendarkk输出错误。排序不正确这永远不会调用(lhs.type-rhs.type),因为距离永远不会相等。那是你的要求。如果先按距离排序,而距离永远不相等,则无法在第二级按类型排序。
Collections.sort(list, new Comparator<Abc>() {
        @Override
        public int compare(Abc lhs, Abc rhs) {
            return Double.compare(lhs.d_distance, rhs.d_distance);
        }
    });