Java Point2D 和类似的
我正在制作 Point2D.Float 类型的 TreeSet,并使用实现 Point2D 类型的compare() 的自定义 Comparable 类创建它。但是,在 TreeSet 上调用“contains”时,出现类转换错误: java.lang.ClassCastException: java.awt.geom.Point2D$Float 无法转换为 java.lang.Comparable
是这样创建的:
private CoordinateComparator coordCompare;
public TreeSet<Point2D.Float> coordSet = new TreeSet<Point2D.Float>(coordCompare);
这是我的比较类:
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;
}
}
对出了什么问题有什么想法吗?我已经被困在这里几个小时试图调试它但无济于事。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
添加我之前的评论作为答案。您需要首先初始化比较器。
@the-alchemist,我猜他得到了 Class Cast Exception 而不是 NPE,因为它试图强制转换为
(Comparator) null
并且由于某种原因在它实际尝试调用之前失败了比较方法。如果没有堆栈跟踪,我不确定。Adding my previous comment as answer. You need to initialize your Comparator first.
@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.