views:

60

answers:

1

I'm making a TreeSet of Point2D.Float type, creating it with a custom Comparable class that implements compare() of Point2D type. However, on calling "contains" on the TreeSet, I get a classcast error: java.lang.ClassCastException: java.awt.geom.Point2D$Float cannot be cast to java.lang.Comparable

The set is created as so:

private CoordinateComparator coordCompare;
public TreeSet<Point2D.Float> coordSet = new TreeSet<Point2D.Float>(coordCompare);

Here is my compare class:

 public class CoordinateComparator implements Comparator<Point2D.Float> {
 public CoordinateComparator() {}

 @Override
 public int compare(Point2D.Float p1, Point2D.Float p2) {
        if (p1.getX() < p2.getX()) 
         return -1;
        if (p1.getX() > p2.getX())
         return 1;
        if (p1.getY() < p2.getY())
         return -1;
        if (p1.getY() > p2.getY())
         return 1;
        return 0;
 }
}

Any ideas on what's going wrong? I've been stuck here for hours trying to debug it to no avail. Thanks.

A: 

Adding my previous comment as answer. You need to initialize your Comparator first.

 public class CoordinateComparator implements Comparator<Point2D.Float> {
 public CoordinateComparator() {}

 @Override
 public int compare(Point2D.Float p1, Point2D.Float p2) {
        if (p1.getX() < p2.getX()) 
         return -1;
        if (p1.getX() > p2.getX())
         return 1;
        if (p1.getY() < p2.getY())
         return -1;
        if (p1.getY() > p2.getY())
         return 1;
        return 0;
 }
}

CoordinateComparator coordCompare = new CoordinateComparator();
TreeSet<Point2D.Float> coordSet = new TreeSet<Point2D.Float>(coordCompare);

@the-alchemist, I'm guessing he's getting the Class Cast Exception and not a NPE because it's trying to cast to do (Comparator) null and for some reason that's failing before it actually tries to call the compare method. Without the stack trace I'm not sure though.

John Engelman