2016-10-06 29 views
1

我正在嘗試使用Collections.sort()對List<Point2D>點進行排序。我相信我正確設置了這個比較器。無論如何,這是拋出一個錯誤說:The method sort(List<T>, Comparator<? superT>) in the type Collections is not applicable for the arguments (List<Point2D>, new Comparator<Point2D.Double>(){})。有人明白我的編譯器爲什麼會拋出這個錯誤嗎?Point2D比較器拋出錯誤

Collections.sort(points, new Comparator<Point2D.Double>() { 
    public int compare(Point2D.Double p1, Point2D.Double p2) { 
     return Double.compare(p1.getX(), p2.getX()); 
    } 
}); 
+0

如果你有Point2D'的'名單,那麼你需要'Point2D'比較。目前你有一個'Point2D.Double'的比較器,它是不一樣的。 – Turamarth

回答

2

只是刪除.Double,你Comparator應該是你的List的相同類型(或類型的母公司)的。

Collections.sort(points, new Comparator<Point2D>() { 
     public int compare(Point2D p1, Point2D p2) { 
      return Double.compare(p1.getX(), p2.getX()); 
     } 
    }); 
+0

「相同類型」表示超類型也是有效的。 – MordechayS

+0

是超級類型也是有效的不是子類型,Point2D.Double是Point2D的子類型 –

+0

我沒有糾正你,只是指出...... :) – MordechayS

0

CollectionsJava documentation,我們可以看到,在方法sort(List<T> list, Comparator<? super T> c),如果ListT然後Comparator可以T類型或其父類(包括T本身)的。

你的情況,你有List<Point2D> & Comparator<Point2D.Double>Point2D.Double不是父類的Point2D

關於<? super T>請參考this link

更改您的代碼如下:

List<Point2D> points = new ArrayList<Point2D>(); 
Collections.sort(points, new Comparator<Point2D>() { 
    public int compare(Point2D p1, Point2D p2) { 
     return Double.compare(p1.getX(), p2.getX()); 
    } 
});