使用比较器
根据距离对对象列表进行排序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);
}
}
如何解决此问题,无法理解错误。我不正确地使用比较器
答案 0 :(得分:1)
您正试图对List<T>
进行排序;你应该使用的是:
Collections.sort(theList, theComparator);
Arrays.sort()
期望T[]
(一个T
数组)不是一回事 - 在很多方面都不是一个。