0

So I'm trying to compare two shape's area using Comparable. I implement it in my class and I'm trying to override compare right now in my LineSegment class which extends my own abstract class Shape.

class LineSegment extends Shape implements Comparable{

public int compareTo(Object object1, Object object2)
      {
         LineSegment ls1 = (LineSegment) object1;
    LineSegment ls2 = this;
    return Double.compare(ls1.getArea(), ls2.getArea());
}



}

Before I had an issue with comparing two doubles and I saw a solution to the problem on here with that return statement and Double. getArea() returns a double area for the LineSegment. So I have ran into this error, any help would be appreciated, thanks- LineSegment is not abstract and does not override abstract method compareTo(java.lang.Object) in java.lang.Comparable class LineSegment extends Shape implements Comparable

3 Answers3

1

In order to implement Comparable, you need to implement compareTo method.

If you want to use Comparator, you should implement compare.

See more here

Use:

class LineSegment extends Shape implements Comparable<LineSegment>{
...

    @Override
    public int compareTo(LineSegment other) {
        return Double.compare(this.getArea(), other.getArea());
    }

}
Community
  • 1
  • 1
BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
  • Right I need to use Comparable, I changed my code and still getting the same error – learning_user7 Nov 15 '14 at 17:36
  • @user4254704 See answer above http://stackoverflow.com/questions/26948604/implementing-comparable-in-java/26948641#26948641 – SMA Nov 15 '14 at 17:36
  • compareTo should get one argument only. see https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html#compareTo(T) – BobTheBuilder Nov 15 '14 at 17:38
1

You need to use Comparator interface instead of Comparable. so your class definition will change to:

class LineSegment extends Shape implements Comparator <LineSegment> {
....//with compare(LineSegment ls1, LineSegment ls2) and you dont need typecasting

Or if you are intending to comparable then you need implementation like:

class LineSegment extends Shape implements Comparable<LineSegment>{
    public int getArea() {...}

    public int compareTo(LineSegment object1)
    {

        return Double.compare(this.getArea(), object1.getArea());
    }
}
SMA
  • 36,381
  • 8
  • 49
  • 73
0

With Comparable, you have to compare one object with this object:

public int compareTo(Object object1){
    LineSegment ls1 = (LineSegment) object1;
    LineSegment ls2 = this;
    return Double.compare(ls1.getArea(), ls2.getArea());
}

this is only rewrited, but you should use <LineSegment>:

class LineSegment extends Shape implements Comparable<LineSegment>{
    public int compareTo(LineSegment ls){
        return Double.compare(ls.getArea(),this.getArea());
    }
}
maskacovnik
  • 3,080
  • 5
  • 20
  • 26