CSE 12 Implementing The Iterator Pattern
CSE 12 Implementing The Iterator Pattern
07
4-2/36
Collection<String> c
Iterator<String> i = c.iterator();
while ( i.hasNext() ) {
String x = i.next(); // get the next String in c
if ( x.length() > 10 ) { // and do something with it
System.out.println(x + is longer than 10 chars);
}
}
Using iterators
07-4/23
Iterable<E> Interface
The Collection<E> interface extends the
Iterable<E> interface, which is defined as follows:
4-6/36
boolean containsAll(Collection<?> c)
boolean isEmpty()
int size()
Iterator<E> iterator()
Object[] toArray()
Iterator<E> Interface
Throws:
NoSuchElementException - if iteration has no more
elements.
4-9/36
07-12/23
07-13/23
07-14/23
find the next element that has not yet been visited
in the backing structure, and...
public LinkedList() {
header = new Node<E>(null,null); // create the dummy node
}
// etc...
Finding the next element to visit is easy: just follow the next
pointer from the last element visited (if that pointer is null, there is
no next element)
Deleting the last element visited requires more thought: you need
to keep a pointer to the predecessor of the last element visited
A partial implementation...
private class LLIter implements java.util.Iterator<E> {
private Node<E> next; // the Node next to be visited
private Node<E> lastReturned; // the Node last visited
private Node<E> pred; // the predecessor of lastReturned
header
next
data
next
data
next
data
15
next
data
10
next
data
40
77
Iterator<Integer> it = x.iterator();
System.out.print(it.next());
System.out.print(it.next());
pred
lastRet
next
it.remove();
System.out.print(it.next());
System.out.print(it.hasNext());
header
next
data
next
data
next
data
15
next
data
10
next
data
40
77
Iterator
expectedModCount
Collection<String> c = new
LinkedList<String>()
c.add(A)
c.add(B)
iter.next()
iter.remove()
c.remove()
operation
iter.next()
throw ConcurrentModificationException
public
public
public
public
public
Class Itr
private class Itr implements Iterator<E> {
/** Index of element to be returned by subsequent call to next. */
int cursor = 0;
/** Index of element returned by most recent call to next or
*
previous.
to remove.
*/
*/
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
Next time
Reading: Gray, Ch 6