user939287
user939287

Reputation: 109

IDE wants class to be abstract with Comparable

Im trying to use the Comparable interface to sort an arrayList of Car objects using a "arrivalTime" field, by using a custom compareTo() method, but it keeps telling me that I can't because the Car object isn't abstract. I can't have it abstract. I need to instantiate the Car objects..

Does anyone know why it would want me to make my class abstract?

Upvotes: 0

Views: 183

Answers (5)

Paulius Matulionis
Paulius Matulionis

Reputation: 23413

You should use Comparable interface like this:

public class Car implements Comparable<Car> {

    private int arrivalTime;

    public Car(int arrivalTime) {
        this.arrivalTime = arrivalTime;
    }

    public int getArrivalTime() {
        return this.arrivalTime;
    }

    @Override
    public int compareTo(Car car) {
        return this.arrivalTime - car.getArrivalTime();
    }

}

To make the actual sort:

LinkedList<Car> cars = new LinkedList<Car>();
cars.add(new Car(20000));
cars.add(new Car(30000));
cars.add(new Car(40000));

Collections.sort(cars);

Take a look at my post here about sorting.

Upvotes: 0

DNA
DNA

Reputation: 42617

Here is a working (if rather crude) example:

public class Cars
{
    static class Car
    {
        Date arrivalTime;
        public Car(Date time)
        {
            arrivalTime = time;
        }
    }

    static class CarComparator implements Comparator<Car>
    {
        @Override
        public int compare(Car o1, Car o2)
        {
            return o1.arrivalTime.compareTo(o2.arrivalTime);
        }       
    }

    public static void main(String[] args)
    {
        List<Car> cars= new ArrayList<Car>();
        // create and add some cars here
        Collections.sort(cars, new CarComparator());
    }
}

Upvotes: 0

rptmat57
rptmat57

Reputation: 3787

you need to use it this way:

public class Car implements Comparable<Car>{

    ...

    @Override
    public int compareTo(Car other) {
    ...
    }
}

Upvotes: 0

Deepak Bala
Deepak Bala

Reputation: 11185

Your method definition inside the class is incorrect. It must be

@Override
public int compareTo(Car o)
{
    return 0;
}

Since the method does not override the one in the interface correctly, the IDE is asking you to mark the class abstract to avoid compilation errors. The other option is to implement the abstract method in the class correctly and get rid of the errors. If you use eclipse press Ctrl + 1 on the class and select the 'Add unimplemented methods' option.

Upvotes: 2

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41240

Seems to be IDE is forcing you make you class abstract or define compareTo method as you implement Comparable interface.

Upvotes: 1

Related Questions