简体   繁体   English

使用比较器对对象列表进行排序

[英]Using Comparator to sort the List of Objects

What i am trying to do : 我正在尝试做的是

Sort the list of objects based on distance using comparator 使用比较器根据距离对对象列表进行排序


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 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);
    }
}

Error i am getting: 我得到的错误:

在此处输入图片说明

How to resolve this, Not able to understand the error. 如何解决此问题,无法理解该错误。 am i using the comparator incorrectly 我是否正确使用比较器

You are trying to sort a List<T> ; 您正在尝试对List<T>进行排序; what you should use is: 您应该使用的是:

Collections.sort(theList, theComparator);

Arrays.sort() expects a T[] (an array of T ) which is not quite the same thing -- in more ways than one. Arrays.sort()需要一个T[]阵列T ),这是不太同样的事情-在很多方面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM