-1

I want to sort Vehicles array based on seats. I tried looking for solutions here, but whenever I pass to compareTo method a Vehicle object, I get error in all my other files with classes for e.g The type Bike must implement the inherited abstract method Comparable.compareTo(Object). Can someone help me with this code?

public abstract class Vehicle implements Comparable {
    
    protected int seats;
    protected int wheels;
    protected int price;
    protected int weight;
    
     public int compareTo(Vehicle o) {
        return -1;
    }

 public static void main(String [] args) {
        Car Lamborghini = new Car(5,4,30000, 1500);
        Bike BMX = new Bike(1,2,300, 15);
        Vehicle Vehicles[] = new Vehicle[2];

        Vehicles[0] = Lamborgini;
        Vehicles[1] = Bmx;

        Arrays.sort(Vehicles);
        for(int i=0;i<Vehicles.length;i++) {
            System.out.println(Vehicles[i]);
        }
    }
Dave
  • 1
  • 1
  • 9
  • 38
  • `The type Bike must implement the inherited abstract method Comparable.compareTo(Object)` where is your implementation of `compareTo` from `Bike`? – KunLun Oct 23 '21 at 18:56

2 Answers2

0

write this

public abstract class Vehicle implements Comparable<Vehicle>

instead of

public abstract class Vehicle implements Comparable

or change

public int compareTo(Vehicle o) {

to

public int compareTo(Object o) {

Also go through a bit of Generics to get better understanding.

notFound
  • 50
  • 8
  • "*or change `public int compareTo(Vehicle o) {` to `public int compareTo(Vehicle o) {`*" - I suspect you wanted to change the parameter in the 2nd method to `Object`? If so: I would highly advice against that approach and only recommend the first solution of properly typing the `Comparable`-interface. – Turing85 Oct 23 '21 at 19:08
  • cant agree more – notFound Oct 23 '21 at 19:09
0

Try it like this.

Change your comparator method to

public int compareTo(Vehicle o) {
       return this.seats < o.seats ? -1 : this.seats > o.seats ? 1 : 0;
}

Now you can pass the Vehicle array to Arrays.sort();

I also have to apologize. I am so used to working with primitive arrays I forgot that you can pass a comparator to Arrays.sort when using Object arrays. So you could also do the following:

Arrays.sort(Vehicles, Comparator.comparing(Vehicle::getSeats)).

or pass any other criteria via a comparator. If you want to reverse the sort you can do.

Arrays.sort(Vehicles, Comparator.comparing(Vehicle::getSeats, Comparator.reverseOrder());

To reverse the order in your current implementation, just change the inequality signs.

WJS
  • 36,363
  • 4
  • 24
  • 39