Iterators
Going through a collection without knowing how it is stored: the iterator and its three methods, the for-each loop, traversing a dictionary, and what happens when the collection is modified during the traversal.
- 26 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- The steps
- Scenarios
A few cards from the deck
Iterator: what is it?
Show the answer
An object that goes through a collection element by element and knows whether any is left, without exposing how the collection is stored.
In Java,
Iterator<E>has three methods:hasNext(),next()andremove(). The same code goes through a list, a set or a dictionary's keys.What does this program produce?
```java
Iterator<Integer> it = List.of(1, 2, 3).iterator();
while (it.hasNext()) {
System.out.println(it.next() + " " + it.next());
}`- It prints
1 2then raisesNoSuchElementException - It prints
1 2then3 3on the second turn - It prints
1 2then3 nullon the second turn - It prints
1 2then ends normally, the loop finished without any error
Show the answer
It prints
1 2then raisesNoSuchElementExceptionhasNext()is checked only once per turn, but the body callsnext()twice. On the second turn only the 3 is left: the firstnext()reads it, the second has nothing left to give.- It prints
An iterator is driven with … to know whether an element is left, and … to read it and move forward.
Show the answer
An iterator is driven with hasNext to know whether an element is left, and next to read it and move forward.
Call
hasNext()before eachnext(). Callingnext()when nothing is left raisesNoSuchElementException.Iterable: what is it?
Show the answer
The Java interface of objects able to provide an iterator: a single method,
iterator().ListandSetimplement it;Mapdoes not, hence the error "for-each not applicable to expression type" onfor (String k : map). A class of ours that implements it can be used in a for-each loop.Removing negative values with an iterator: which step comes after "Get the list's iterator"?
- Read the current element with next()
- Compare that element with 0
- Test hasNext() to know whether an element is left
- Call remove() on the iterator if the element is negative
Show the answer
Test hasNext() to know whether an element is left
next()must come beforeremove(), which removes the elementnext()just returned. ThehasNext()test opens each turn and guards againstNoSuchElementException.