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
Strings. So there has to be some casting.
The first method
numWordsOfLength has you implement the method to count how many Strings of a set length are in
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.
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.
Just like the previous method we have to cast the element we’re getting to a String so that we can use the
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.
Want to stay in touch and keep up to date with the latest posts @ CompSci.rocks?