0

I'm learning Java and doing some simple programming problems. One of them is to implement the Comparable interface in an Octagon class, to allow ranking of octagons based on their side length. Here is a snippet of my code:

class Octagon implements Comparable
  {
    private double side;

    public Octagon(double side)
    {
      this.side = side;
    }

    public double getSide()
    {
      return side;
    }

    @Override
    public int compareTo(Octagon oct)
    {
      /*
      if (this.getSide()==oct.getSide())
        return 0;
      return this.getSide()>oct.getSide()?1:-1;
      */

      /*
      if(this.getSide()==oct.getSide())
        return 0;
      else if (this.getSide()<oct.getSide())
        return 1;
      else
        return -1;
      */

      /*
      if (this.getSide()>oct.getSide())
        return 1;
      else if (this.getSide() == oct.getSide())
        return 0;
      else
        return -1;
      */

      /*
      if(this.getSide()<oct.getSide())
        return -1;
      else if (this.getSide() == oct.getSide())
        return 0;
      else
        return -1;
      */
      /*
      if(this.getSide()<oct.getSide())
        return -1;
      else if (this.getSide()>oct.getSide())
        return 1;
      else
        return 0;
      */
      /*
      if(this.getSide()>oct.getSide())
        return 1;
      else if (this.getSide()<oct.getSide())
        return -1;
      else
        return 0;
      */
    }
  }

I've tried every possible permutation for comparing the two sides as you can see in all the commented-out blocks, and it just seems as if the compiler randomly complains about the method not overriding the abstract compareTo(T o) method in Comparable sometimes and then it suddenly doesn't other times. I really don't know what's going on here. Any help is appreciated.

1 Answers1

2

You need to have it like this:

class Octagon implements Comparable<Octagon>{//Generic allows compiler to have Octagon as param
   @Override
   public int compareTo(Octagon o) {
      return 0;
   }
}

or

class Octagon implements Comparable{//No generic used. Allows to compare any object(s)
       @Override
       public int compareTo(Object o) {
          return 0;
       }
}
Karthik R
  • 5,523
  • 2
  • 18
  • 30
  • ahhh I see. But is this a new requirement in Java 8? Examples in the book I'm following and various websites don't seem to specify the object type –  Sep 18 '15 at 04:14
  • @user141554 Generics are since Java 5, JDK 1.5, however, the websites you mention will have option 2 that i have mentioned. This is not with Java 8, as the code would work for even Java 5 if you try. If the answer is fine, mark the answer and close the thread :) – Karthik R Sep 18 '15 at 04:16