Home > Back-end >  How to sort array of objects based on object value?
How to sort array of objects based on object value?

Time:10-24

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

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • java
  • Related