Rewrite compareTo method

Report a typo

Let's rewrite our code from the topic. Change it so that the natural ordering will sort elements by their numbers and also by their models.

public class Car implements Comparable<Car> {
    private int number;
    private String model;
    private String color;
    private int weight;

    // constructor

    // getters, setters

    @Override
    public int compareTo(Car otherCar) {
        // change it!
        return Integer.valueOf(getNumber()).compareTo(otherCar.getNumber());
    }

}

public static void main(String[] args) {
    List<Car> cars = new ArrayList<>();
    Car car1 = new Car(876, "Volvo", "white", 1400);
    Car car2 = new Car(345, "Mercedes", "black", 2000);
    Car car3 = new Car(470, "BMW", "blue", 1800);
    cars.add(car1);
    cars.add(car2);
    cars.add(car3);

    Collections.sort(cars);
    System.out.println(cars);
}
Select one option from the list
___

Create a free account to access the full topic