WordList Solution

The WordList free response question on the 2004 AP Computer Science exam has you working with an ArrayList of Strings and checking their lengths.

In addition to working with the ArrayList you’ll need to understand that the list myList contains references to Objects, not Strings. So there has to be some casting.

Part A

The first method numWordsOfLength has you implement the method to count how many Strings of a set length are in myList.

public int numWordsOfLength( int len ) {
    int cnt = 0;
    for (Object w: myList) {
        String s = (String)w; 
        if (s.length() == len) {
            cnt++;
        }
    }
    return cnt; 
    
}

Notice that the first line in the loop pulls out an Object named w and casts it to a String named s. We have to do this because we’re using the length() method, and Objects don’t have that method.

Part B

Like Part A we’re going through myList and checking the length of the Strings it contains. This time though we want to remove any Strings that are a set length.

public void removeWordsOfLength( int len ) {
    for (int i=myList.size() - 1; i>=0; i--) {
        String s = (String)myList.get(i);
        if (s.length() == len) {
            myList.remove(i); 
        }
    }
}

Just like the previous method we have to cast the element we’re getting to a String so that we can use the length method.

We couldn’t use a for each loop this time. If you try to remove an element of a list while inside a for each loop you’ll get a ConcurrentModificationException. So I used a for loop instead. And I went backwards because that keeps you from skipping elements as you remove them.

Leave a Reply

Your email address will not be published. Required fields are marked *