Part (a)
// postcondition: returns the number of words in this WordList that
// are exactly len letters long
public int numWordsOfLength(int len)
{
int count = 0;
for (int i = 0; i < myList.size(); i++)
if (((String)myList.get(i)).length() == len) 1
count++;
return count;
}
Notes:
- The cast to
String is necessary to call its length method.
Part (b)
// postcondition: all words that are exactly len letters long
// have been removed from this WordList, with the
// order of the remaining words unchanged
public void removeWordsOfLength(int len)
{
int i = 0;
while (i < myList.size()) 1
{
if (((String)myList.get(i)).length() == len)
myList.remove(i); 2
else
i++;
}
} 3
Notes:
- A
while loop is more convenient for a traversal
with removals than a for loop.
- When we remove a value,
myList.size()
is decremented and the indices of the subsequent
values are decremented by one.
In that case, we don't increment i .
- A solution with an iterator is acceptable, too,
and it is actually shorter and safer:
public void removeWordsOfLength(int len)
{
Iterator iter = myList.iterator();
while (iter.hasNext())
{
if (((String)iter.next()).length() == len)
iter.remove();
}
}
|