Limited access

Upgrade to access all content for this subject

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 pets in ascending order by pet type (cat, dog, guinea pig, etc.), then by name.

Which method below would BEST facilitate that?

A
public int compareTo(Object obj) 
{
    return type.compareTo(((Pet) obj).type) * name.compareTo(((Pet) obj).name);
}
B
public int compareTo(Object obj) 
{
    Pet other = (Pet) obj;
    if (type.compareTo(other.type)==0)
        if (name.compareTo(other.name)==0)
            return 0;
        else
        if (name.compareTo(other.name)<0)    
            return -1;
        else
            return 1;
    else
    if (type.compareTo(other.type)<0)
        if (name.compareTo(other.name)==0)
            return 0;
        else
        if (name.compareTo(other.name)<0)    
            return -1;
        else
            return 1;
    else
    if (name.compareTo(other.name)==0)
        return 0;
    else
    if (name.compareTo(other.name)<0)    
        return -1;
    else
        return 1;
}
C
public int compareTo(Object obj) 
{
    Pet other = (Pet) obj;
    if (type.compareTo(other.type)==0)
        if (name.compareTo(other.name)==0)
            return 0;
        else
        if (name.compareTo(other.name)<0)    
            return -1;
        else
            return 1;
    else
    if (type.compareTo(other.type)<0)
        return -1;
    return 1;
}
D
public int compareTo(Object obj) 
{
    Pet other = (Pet) obj;
    boolean typesEqual = false;
    if (type.equals(other.type))
        typesEqual = true;
    if (typesEqual && name.compareTo(other.name)==0)
        return 0;
    if (typesEqual && name.compareTo(other.name)<0)    
        return -1;
    if (typesEqual && name.compareTo(other.name)>0)    
        return 1;
    return 0;
}
E
public int compareTo(Object obj) 
{
    Pet other = (Pet) obj;
    if (name.compareTo(other.name)==0)
        if (type.compareTo(other.type)==0)
            return 0;
        else
        if (type.compareTo(other.type)<0)
            return -1;
        else
            return 1;
    else
    if (name.compareTo(other.name)<0)
        return -1;
    return 1;
}
Select an assignment template