Limited access

Consider the following class.

public class Car implements Comparable
{
private double miles;
private double gallons;

//constructor and other methods not listed

// calculate the miles per gallon
public double calcMPG()
{
return miles/gallons;
}
}


When sorting an array of Car objects, the cars need to be sorted in ascending sequence in the order of their miles per gallon (MPG). In other words, a car that has an MPG of 20 is less than a car with an MPG rating of 30.

Which of the following methods should be added to the Car class so that standard sort algorithms (such as Arrays.sort) will sort the array of Car objects properly?

A
public boolean equals(Object obj)
{
Car other = (Car) obj;
if (calcMPG() == other.calcMPG())
return true;
return false;
}

B
public int compareTo(Car other)
{
if (calcMPG() < other.calcMPG())
return -1;
if (calcMPG() == other.calcMPG())
return 0;
return 1;
}

C
public int compareTo(Object obj)
{
if (calcMPG() < obj.calcMPG())
return -1;
else
if (calcMPG() > obj.calcMPG())
return 1;
else
return 0;
}

D
public int compareTo(Object obj)
{
Car other = (Car) obj;
if (calcMPG() < other.calcMPG())
return -1;
if (calcMPG() == other.calcMPG())
return 0;
return 1;
}

E
public int equals(Object obj)
{
Car other = (Car) obj;
if (calcMPG() < other.calcMPG())
return -1;
else
if (calcMPG() > other.calcMPG())
return 1;
else
return 0;
}

Select an assignment template