Hi i'm having trouble implementing the compareTo method. I've looked for answers but nothing has been any help. I'm trying to fill a TreeSet with various sizes of circles. I need compareTo in my circle class to be able to store them this way.
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;
}
}
}
Edit: Thanks I was forgetting something: Circle is not abstract and does not overide abstract method compareTo(Object) in Comparable
Thanks for the help on that, now that I have gotten down to testing the class, when try to add a circle to the treeset this exception pops up any ideas,
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)