The following match method is intended to remove all elements divisible by key from an ArrayList of integers. The removed elements are added to a new ArrayList, which the method returns.
public static ArrayList<Integer> match(ArrayList<Integer> numList, int key)
{
ArrayList<Integer> returnList = new ArrayList<Integer>();
int i = 0;
while (i < numList.size())
{
int num = numList.get(i);
if (num % key == 0)
{
numList.remove(i);
returnList.add(num);
}
i++;
}
return returnList;
}
For example, if numList contains [5, 2, 10, 20, 16] and key is 5, the method is expected to modify numList to [2, 16] and return an ArrayList containing [5, 10, 20].
Which of the following statements best explains why the method does not always work as intended?
The method skips some elements of numList during the traversal.
The method causes an IndexOutOfBoundsException to be thrown.
The method fails to correctly determine whether an element of numList is divisible by key.
The method causes a NullPointerException to be thrown when no matches are found.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE