Complete the method body so that it removes all strings
in list beginning with the letter initial.
It should assume that list contains only String
objects.
Recall the following instance methods defined for the ArrayList class.public static void removeAll(ArrayList list, char initial) { }
This is slightly tricky in that you can't just go through the list removing each element beginning with the letter: Say two adjacent elements begin with the letter. When we remove the first one, the second element shifts into the slot from which we just removed. The program needs some way of checking that element again.
My technique for handling this is to go through the list backwards. It's also possible to address the problem by using a while loop within the for loop (so you repeatedly check whether the current element begins with the letter) or by decrementing the counter when an item is removed (so that the next iteration revisits that position after re-incrementing the counter to its previous position).
public static void removeAll(ArrayList list, char initial) { for(int i = list.size() - 1; i >= 0; i--) { String elt = (String) list.get(i); if(elt.charAt(0) == initial) { list.remove(i); } } }