?

AP® Computer Science A

Free Version

Upgrade subject to access all content

Difficult

Sorting Pet Objects by Pet Type

APCSA-1NK9EV

Consider the following Pet class.

public class Pet implements Comparable
{
    private String type, name;
    private int age;
    private int weight;

    public Pet(String typ, String nam, int howOld, int wt)
    {
        type = typ;
        name = nam;
        age = howOld;
        weight = wt;
    }
    // other data and methods not shown
}

We would like to anticipate that other classes may want to sort Pet in ascending order by pet type (cat, dog, guinea pig, etc.) using standard sort algorithms.

Which method below would BEST facilitate this type of sorting?

A
public boolean equals(Object obj)
{
    Pet other = (Pet) obj;
    if (type.equals(other.type))
        return true;
    return false;
}
B
public int compareTo(Object obj) 
{
    return type.compareTo(((Pet) obj).type);
}
C
public int compareTo(Object obj) 
{
    Pet other = (Pet) obj;
    if (type == other.type)
        return 0;
    else
    if (type < other.type)
        return -1;
    return 1;
}
D
public int compareTo(Pet other) 
{
    if (type.compareTo(other.type)==0)
        return 0;
    else
    if (type.compareTo(other.type<0)
        return -1;
    return 1;
}
E
public int compareTo(Object obj) 
{
    Pet other = (Pet) obj;
    if (this.type.compareTo(other.type)==0)
        return 0;
    else
        return this.type.compareTo(other.type) * -1;
}