Learn AP Comp Sci

Problem of the Day

Tuesday, December 9, 2025


Problem:

A partial listing of the Cookie class is given here.

public class Cookie
{
private String type;

public Cookie(String type)
{
this.type = type;
}

public String getType()
{
return type;
}
}

A separate Runner class contains the following static method.

public static void crazy(ArrayList<Cookie> cookies, String type)
{
int i = 0;
while (i < cookies.size())
if (cookies.get(i).getType().equals(type))
cookies.remove(i);
else
i++;
}

What does this static method crazy do?

  1. identifies how many cookies of the indicated type there are
  2. identifies how many cookies in the array are not of the indicated type
  3. removes all cookies that are not of the specified type from the ArrayList cookies
  4. removes all of the cookies of the indicated type from the ArrayList cookies

Show solution:

The correct answer is d. The method crazy uses a while-loop to go through the ArrayList. Cookies of the specified type are removed using the remove method, and the index counter i is not incremented (so we can examine the next cookie that has moved into this position). If this isn't a cookie of interest, we do increment i and continue working through the list.