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.

  1. Concepts
  2. Questions
  3. Sort and link
  4. The steps
  5. 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() and remove(). 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 2 then raises NoSuchElementException
    • It prints 1 2 then 3 3 on the second turn
    • It prints 1 2 then 3 null on the second turn
    • It prints 1 2 then ends normally, the loop finished without any error
    Show the answer

    It prints 1 2 then raises NoSuchElementException

    hasNext() is checked only once per turn, but the body calls next() twice. On the second turn only the 3 is left: the first next() reads it, the second has nothing left to give.

  • 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 each next(). Calling next() when nothing is left raises NoSuchElementException.

  • Iterable: what is it?

    Show the answer

    The Java interface of objects able to provide an iterator: a single method, iterator().

    List and Set implement it; Map does not, hence the error "for-each not applicable to expression type" on for (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 before remove(), which removes the element next() just returned. The hasNext() test opens each turn and guards against NoSuchElementException.