使用Comparator对对象列表进行排序

时间:2015-11-15 02:20:19

标签: java android

我想做什么

使用比较器

根据距离对对象列表进行排序
private Point getNearestPixelValue(int pixlX, int pixlY) {

        LinkedList<DistancePoint> mList=new LinkedList<DistancePoint>();

        for (int i = 0; i < modelModFile.getStroke_paths().size(); i++) {
            for (int j = 0; j < modelModFile.getStroke_paths().get(i).getMain_stroke().size(); j++) {

                if (j < modelModFile.getStroke_paths().get(i).getMain_stroke().size() - 1) {
                    String a = modelModFile.getStroke_paths().get(i).getMain_stroke().get(j).getStroke();
                    String[] fA = a.split(",");
                    Point p1 = new Point(Integer.valueOf(fA[0]), Integer.valueOf(fA[1]));
                    Point p2 = new Point(pixlX, pixlY);
                    //Add the calculated distance to a integerArray
                    DistancePoint mObj=new DistancePoint(p2,calDistBtwTwoPixels(p1, p2));
                    mList.add(mObj);
                }
            }
        }

        //Sort the array
        Arrays.sort(mList, DistancePoint.distanceComparator);

        //Return the nearest point
        return mList.get(0).getmPoint();
    }

DistancePoint.java

public class DistancePoint implements Comparable<DistancePoint>{

    int mDistance;
    Point mPoint;

    public DistancePoint(Point mPoint, int mDistance) {
        super();
        this.mPoint = mPoint;
        this.mDistance = mDistance;
    }


    public int getmDistance() {
        return mDistance;
    }

    public void setmDistance(int mDistance) {
        this.mDistance = mDistance;
    }

    public Point getmPoint() {
        return mPoint;
    }

    public void setmPoint(Point mPoint) {
        this.mPoint = mPoint;
    }


    public static Comparator<DistancePoint> distanceComparator = new Comparator<DistancePoint>() {

        @Override
        public int compare(DistancePoint e1, DistancePoint e2) {
            return (int) (e1.getmDistance() - e2.getmDistance());
        }
    };


    @Override
    public int compareTo(DistancePoint distancePoint) {
        //let's sort the employee based on distance in ascending order.
        return (this.mDistance - distancePoint.mDistance);
    }
}

我得到的错误:

enter image description here

如何解决此问题,无法理解错误。我不正确地使用比较器

1 个答案:

答案 0 :(得分:1)

您正试图对List<T>进行排序;你应该使用的是:

Collections.sort(theList, theComparator);

Arrays.sort()期望T[](一个T数组)不是一回事 - 在很多方面都不是一个。