1

I'm trying to sort a List<Point2D> of points using Collections.sort(). I believe I set up this comparator correct. Anyways, it's throwing an error saying: The method sort(List<T>, Comparator<? superT>) in the type Collections is not applicable for the arguments (List<Point2D>, new Comparator<Point2D.Double>(){}). Does anybody understand why my compiler is throwing this error?

Collections.sort(points, new Comparator<Point2D.Double>() {
    public int compare(Point2D.Double p1, Point2D.Double p2) {
        return Double.compare(p1.getX(), p2.getX());
    }
});
Andy S
  • 15
  • 3
  • If you have a list of `Point2D` then you need a comparator for `Point2D`. Currently you have a comparator for `Point2D.Double` which is not the same. – Turamarth Oct 06 '16 at 07:56

2 Answers2

2

just remove .Double , your Comparator should be of same type (or parent of type) of your List.

   Collections.sort(points, new Comparator<Point2D>() {
        public int compare(Point2D p1, Point2D p2) {
            return Double.compare(p1.getX(), p2.getX());
        }
    });
Amber Beriwal
  • 1,468
  • 13
  • 26
Amer Qarabsa
  • 5,678
  • 3
  • 16
  • 31
0

From the Java documentation of Collections, we can see that in method sort(List<T> list, Comparator<? super T> c), if List is of T then Comparator can be of type T or its parent classes (including T itself).

In your case, you have List<Point2D> &Comparator<Point2D.Double>, and Point2D.Double is not the parent class of Point2D.

Regarding <? super T> refer this link.

Change your code to following:

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());
    }
});
Community
  • 1
  • 1
Amber Beriwal
  • 1,468
  • 13
  • 26