当尝试将对象添加到我的 TreeSet 时,会弹出此异常。
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)
我在我的主要方法中所做的只是创建 TreeSet、创建一个对象并将其添加到集合中。
下面是主要方法:
class CircleTreeSet {
public static void main(String[] args) {
TreeSet<Circle> cs = new TreeSet<Circle>();
Circle circle1 = new Circle("circle1", 1);
cs.add(circle1);
}
}
这是课程:
class Circle extends Shape implements Comparable<Circle> {
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) {
return name.compareTo(c.name);
}
}