Search code examples
javainterfacecomparable

Java: Problems implementing the Comparable interface


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.


Solution

  • 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;
           }
    }