?

AP® Computer Science A

Free Version

Upgrade subject to access all content

Difficult

Updating the Weight from an ArrayList of Objects

APCSA-ZLNKT4

Consider the following 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 weight)
    {
        type = typ;
        name = nam;
        age = howOld;
        this.weight = weight;
    }

    public int getWeight()
    {
        return weight;
    }

    public void setWeight(int wt)
    {
        weight = wt;
    }

    public boolean equals(Object obj)
    {
        Pet other = (Pet) obj;
        if (name.equals(other.name) && type.equals(other.type))
        {
            return true;
        }
        return false;
    }

    // other data and methods not shown
}

A pet is equal to another pet if its type and name are exactly the same. Which of the following methods would take an array list of Pet objects, find the Pet that matches the searchPet parameter and update the weight of the Pet in the array list with the weight from searchPet?

A
public static void updatePetWeight(ArrayList<Pet> pets, Pet searchPet)
{
    for (int i=0; i<pets.size(); i++)
    {
        if (pets.get(i).equals(searchPet))
            pets.get(i).setWeight(pets.get(i).getWeight());
    }
}
B
public static void updatePetWeight(ArrayList<Pet> pets, Pet searchPet)
{
    for (Pet p : pets)
    {
        if (p.equals(searchPet))
            searchPet.setWeight(p.getWeight());
    }
}
C
public static void updatePetWeight(ArrayList<Pet> pets, Pet searchPet)
{
    for (Pet p : pets)
    {
        if (p.equals(searchPet))
            pets.setWeight(searchPet.getWeight());
    }
}
D
public static void updatePetWeight(ArrayList<Pet> pets, Pet searchPet)
{
    for (Pet p : pets)
    {
        if (p.equals(searchPet))
            p.setWeight(searchPet.getWeight());
    }
}
E
public static void updatePetWeight(ArrayList<Pet> pets, Pet searchPet)
{
    for (int i=0; i<pets.size(); i++)
    {
        if (pets.get(i).equals(searchPet))
            pets.get(i).getWeight(pets.get(i).setWeight());
    }
}