|
Iterators
import java.util.Iterator;
The List and Set collections provide iterators, which are objects that allow going over all the elements of a collection in sequence. The java.util.Iterator<E> interface provides for one-way traversal and has three methods listed below.
Below is my IteratorsExample.java class. Feel free to run it and see an example of iterators in action.
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
public class IteratorsExample {
public static void main(String[] args){
List myList = new ArrayList();
myList.add("a");
myList.add("b");
myList.add("c");
myList.add("d");
myList.add("e");
myList.add("f");
//iterator
Iterator myItr = myList.iterator();
while(myItr.hasNext())
System.out.println(myItr.next());
}
}
| Result | Method |
Description |
b = |
itr.hasNext() |
true if there are more elements for the iterator. |
obj = |
itr.next() |
Returns the next object. If a generic list is being accessed, the iterator
will return something of the list's type. |
|
itr.remove() |
Removes the last recent element that was returned by next.
WARNING: You cannot call itr.remove() without having called itr.next() . |
Common Issues involved with Iterators
Predict the output of the following code
while(it.hasNext())
{
if(it.next().equals("sue") || it.next().equals("john")
it.remove()
}
AP Practice Question
The following class WordList is designed to store and manipulate a list of words. The incomplete class declaration is show below. You will be asked to implement two methods.
public class WordList{
private ArrayList<String> myList ;// contain Strings made up of letters
//postcondition: returns the number of words in this WordList that are exactly len letters long
public int numWordsOfLength(int len)
{/*to be implemented in part(a)*/ }
}
(a)
Write the WordList method numWordsOfLength. This method returns the number of words in the WordList that are exactly len letters long.
Question 2) Write the WordList method removeWordsOfLength. This method removes all words from the WordList that are exacty len long, leaving the order of the remainaing words unchanged. For example, assume that the instance variable mylist of the WordList animals contains the following.
["cat","mouse","frog","dog","dog"]
| Method call |
MyListAfter the call
|
| animals.removeWordsOfLength(4); |
["cat","mouse","frog","dog","dog"]
|
| animals.removeWordsOfLength(3); |
[ "mouse" ]
|
| animals.removeWordsOfLength(2); |
[ "mouse" ]
|
Top
|