Question 5-2

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.

public static void removeAll(ArrayList list, char initial) {



}
Recall the following instance methods defined for the ArrayList class.
Object get(int index)
Returns the object at index index of the list.
Object remove(int index)
Removes the object at index index of the list, shifting objects at that index and beyond to fill the gap. Returns the removed object.
int size()
Returns the number of elements in the list.
Also recall the following instance method defined for the String class.
char charAt(int pos)
Returns the character at index pos of the string.

Solution

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);
        }
    }
}

Back to 8:00 Quiz 5