2011-03-03 34 views
3

我有一個點對象列表,我想按某個座標排序,比如說x值。 Java是否提供了任何有用的機制,還是應該利用其中一種常見的排序算法?用Java對點列表排序

回答

13

是創建一個自定義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() { 
    } 
} 

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()); 
} 
}); 
+1

簡直超級。非常感謝。 – Abdul 2015-09-03 06:04:18

5

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

您應該讓您的Point類實現Comparable接口或使用您自己的Comparator對象提供sort()方法,該對象告訴sort()如何排序對象。這裏有很多例子。