Limited access

Upgrade to access all content for this subject

Consider the following class.

public class Car implements Comparable
{
    private String make;
    private String model;
    private int mileage;

    public Car (String mk, String md, int miles)
    {
        make = mk;
        model = md;
        mileage = miles;
    }

    public String toString()
    {
        return make + " " + model + " " + mileage;
    }
}

An array of Car objects needs to be sorted by mileage in descending order, then by model in ascending order. For example, consider the following section of code from a main method in a client class:

Car [] cars = { new Car ("Ford", "Mustang", 95000),
                new Car ("Ford", "Mustang", 70000),
                new Car ("Honda", "Accord", 10000),
                new Car("Toyota", "Camry", 50000),
                new Car("Honda", "Accord", 70000),
                new Car("Toyota", "Corolla", 10000) };
Arrays.sort(cars);
for (int i=0; i<cars.length; i++)
{
    System.out.println(cars[i]);
}

The output of this sort should be:

Ford Mustang 95000
Honda Accord 70000
Ford Mustang 70000
Toyota Camry 50000
Honda Accord 10000
Toyota Corolla 10000

Which of the following methods need to be coded in the Car class to accomplish this?

A
public int compareTo(Object obj)
{                            
    Car other = (Car) obj;      
    if (mileage > other.mileage && model.compareTo(other.model)<0)
        return -1;
    else 
    if (mileage < other.mileage && model.compareTo(other.model)>0)
        return 1;
    else
        return 0;
 }
B
public int compareTo(Object obj)
{                            
    Car other = (Car) obj;      
    if (mileage > other.mileage)
        return -1;
    if (mileage < other.mileage)
        return 1;
    if (model.compareTo(other.model)<0)
        return -1;
    if (model.compareTo(other.model)>0)
        return 1;
    return 0;
 }
C
public int compareTo(Object obj)
{                            
    Car other = (Car) obj;      
    if (mileage > other.mileage && model.compareTo(other.model)>0)
        return 1;
    else 
    if (mileage < other.mileage && model.compareTo(other.model)<0)
        return -1;
    else
        return 0;
 }
D
public int compareTo(Object obj)
{                            
    Car other = (Car) obj;      
    if (model.compareTo(other.model)<0)
        return -1;
    if (model.compareTo(other.model)>0)
        return 1;
    if (mileage > other.mileage)
        return -1;
    if (mileage < other.mileage)
        return 1;
    return 0;
 }
E
public int compareTo(Object obj)
{                            
    Car other = (Car) obj;      
    if (mileage == other.mileage)
        return 0;
    if (mileage < other.mileage)
        return 1;
    if (mileage > other.mileage)
        return -1;
    if (model.compareTo(other.model)<0)
        return -1;
    if (model.compareTo(other.model)>0)
        return 1;
    return 0;
 }
Select an assignment template