74.9k views
5 votes
Consider the following method intended to modify the parameter names by removing all instances of the String n.

public static void removeNames (ArrayList names, String n) { for (/* Missing Code */) { if (names.get(i).equals(n)) { names.remove(i); } } }

Which of the following could correctly replace /* Missing Code */ so that removeNames works as intended?

int i = 0; i < names.size(); i--

int i = names.size() - 1; i >= 9; i++

int i = 0; i < names.size(); i++

int i = names.size() - 1; i >=0; i--

none of the above. The code has an error.

User Ronny
by
4.2k points

1 Answer

6 votes

Answer:

int i = 0; i < names.size(); i++

Step-by-step explanation:

The ArrayList must be read in the forward direction, and it is going to start from 0 certainly. Also, the iteration is going to end when i is exactly one less than the size of the ArrayList. And this is possible only if we choose the option mentioned in the Answer section. In this, i starts from 0 and iterates till i is one less than name.size() which is the size of the ArrayList.

User Rhathin
by
4.6k points