简体   繁体   English

Java Point2D和Comparable

[英]Java Point2D and Comparable

I'm making a TreeSet of Point2D.Float type, creating it with a custom Comparable class that implements compare() of Point2D type. 我正在制作Point2D.Float类型的TreeSet,使用自定义Comparable类创建它,该类实现Point2D类型的compare()。 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 但是,在TreeSet上调用“contains”时,我得到一个classcast错误: java.lang.ClassCastException: java.awt.geom.Point2D$Float cannot be cast to java.lang.Comparable强制转换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. 谢谢。

Adding my previous comment as answer. 添加我以前的评论作为答案。 You need to initialize your Comparator first. 您需要先初始化Comparator。

 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. @ the-alchemist,我猜他正在获得Class Cast Exception而不是NPE,因为它试图强制转换(Comparator) null并且由于某种原因它在实际尝试调用compare方法之前失败了。 Without the stack trace I'm not sure though. 没有堆栈跟踪,我不确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM