Java的:如何自定义排序ArrayList类型 [英] Java: How to sort custom type ArrayList

查看:264
本文介绍了Java的:如何自定义排序ArrayList类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义类型位置(X,Y,Z),现在我创建一个的ArrayList<位置> ,我想这个排序由数组z的值进行排序,从小到大,我怎么能做到这一点使用 Col​​lections.sort 或有任何其他有效的排序方法?

当我尝试使用

 公共类PositionComparator实现比较<地位与GT; {        @覆盖
        公众诠释比较(位置O1,O2的位置){
            // TODO自动生成方法存根
            返回o1.height()的compareTo(o2.height())。        }    }

得到一个错误

 的基本类型的双能不能调用的compareTo(双)


解决方案

尝试

  Col​​lections.sort(sortlist中,新的比较<&定位GT;(){
            公众诠释比较(位置P1,​​位置P2){
                返回p1.z- p2.z;
            }
        });

I have a custom type Position(x,y,z),now I create a ArrayList<Position>, i want to sort this array ordered by the value of z, from small to bigger,how can i do that using Collections.sortor is there any other efficient sorting method?

When I try to use

public class PositionComparator implements Comparator<Position> {

        @Override
        public int compare(Position o1, Position o2) {
            // TODO Auto-generated method stub
            return o1.height().compareTo(o2.height());

        }

    }

get an error

Cannot invoke compareTo(double) on the primitive type double

解决方案

try

Collections.sort(SortList, new Comparator<Position>(){
            public int compare(Position p1, Position p2) {
                return p1.z- p2.z;
            }
        });

这篇关于Java的:如何自定义排序ArrayList类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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