嗨,我在实现 compareTo 方法时遇到了麻烦。我一直在寻找答案,但没有任何帮助。我正在尝试用各种大小的圆圈填充 TreeSet。我需要在我的圈子类中使用 compareTo 才能以这种方式存储它们。
import java.util.*;
import java.lang.*;
abstract class Shape
{
private String name; //e.g."circlel", "rectangle3"
Shape(String name0)
{
name = name0;
}
abstract double area (); // area of shape
abstract double perim(); // length of perimeter of shape
void put()
{ // display shape details
System.out.println(name + " with area " + area()
+ " and perimeter " + perim() );
}
}
class Circle extends Shape implements Comparable
{
private static String name;
private int radius;
Circle(String n, int r)
{
super(n);
radius = r;
}
public double area()
{
return Math.PI * radius * radius;
}
public double perim()
{
return 2 * Math.PI * radius;
}
public int compareTo(Circle c)
{
if(c.name == name && c.radius == radius)
{
return 0;
}
else
{
return 1;
}
}
}
编辑:谢谢我忘记了一些事情:Circle 不是抽象的,并且不会覆盖 Comparable 中的抽象方法 compareTo(Object)
感谢您的帮助,既然我已经开始测试课程,当尝试向树集中添加一个圆圈时,这个异常会弹出任何想法,
Exception in thread "main" java.lang.NullPointerException
at Circle.compareTo(Shape.java:47)
at Circle.compareTo(Shape.java:23)
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at CircleTreeSet.main(CircleTreeSet.java:24)