简体   繁体   中英

Implementing Comparable in Java

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

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());
    }

}

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());
    }
}

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());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM