Problem of the Day
Problem:
The remove
method given here takes an ArrayList<Integer>
as a parameter and removes values from it.
public static void remove(ArrayList<Integer> vals)
{
int i = 0;
while (i < vals.size())
{
boolean found = false;
int j = i + 1;
while (j < vals.size())
{
if (vals.get(j) == vals.get(i))
{
found = true;
vals.remove(j);
}
else
{
j++;
}
}
if (found)
vals.remove(i);
i++;
}
}
Which best describes the function of the remove
method?
- It removes any two numbers in the list that have the same value.
- It removes any numbers that occur more than once in the list.
- It removes any numbers that occur both at the beginning of the list and elsewhere in the list.
- It removes the first occurrence of any number in the list that appears more than once.
The correct answer is b. The i
-loop iterates through the list, while the j
-loop identifies values in the rest of the list that match anything at position i
. If a match is found at index j
, that value is removed, and the boolean flag variable found
is set to true
so that later on the initial matching value (at i
) can be removed from the list as well.