Sorting a list of points with Java 
我有一个点对象列表,我想按某个坐标排序,比如x值。Java是否提供了任何有用的机制,或者我应该使用一种常见的排序算法吗?
是,创建自定义Comparator,并使用它对点列表进行排序
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 
 | 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() {
    }
} | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 
 | 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());
}
}); | 
在Point类中,您应该实现与泛型类型类似的接口,并使用Collections.sort(java.util包)对List进行排序。
假设:
| 12
 3
 4
 5
 6
 7
 
 | class Point implements Comparable< Point>{
    int  compareTo(Point  other){ /* your logic */}
} 
List< Point>  list = new  ArrayList< Point>();
/* adding points */
Collections .sort( list); | 
您可以使用bean比较器之类的工具,这样就不必一直创建自定义比较器。
您应该让您的点类实现可比较的接口,或者为sort()方法提供您自己的comparator对象,它告诉sort()如何排序对象。这里有很多例子。