Note that there are some explanatory texts on larger screens.

plurals
  1. POcompareTo() implementation problems
    primarykey
    data
    text
    <p>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. </p> <pre><code>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 &amp;&amp; c.radius == radius) { return 0; } else { return 1; } } } </code></pre> <p>Edit: Thanks I was forgetting something: Circle is not abstract and does not overide abstract method compareTo(Object) in Comparable</p> <p>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,</p> <pre><code>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) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload