Jig*_*shi 19
是创建自定义Comparator,并使用它来对点列表进行排序
class Point{
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point() {
}
}
Run Code Online (Sandbox Code Playgroud)
List<Point> points = new ArrayList<Point>();
points.add(new Point(1, 2));
points.add(new Point(60, 50));
points.add(new Point(50, 3));
Collections.sort(points,new Comparator<Point>() {
public int compare(Point o1, Point o2) {
return Integer.compare(o1.getX(), o2.getX());
}
});
Run Code Online (Sandbox Code Playgroud)
在Point类中,您应该使用泛型类型实现Comparable接口<Point>并使用Collections.sort(java.util包)进行排序List<Point>
假设:
class Point implements Comparable<Point>{
int compareTo(Point other){ /* your logic */}
}
List<Point> list = new ArrayList<Point>();
/* adding points */
Collections.sort(list);
Run Code Online (Sandbox Code Playgroud)