for (E e : list) works on any class that implements Iterable<E>. In IterableList, write a singly linked list Chain<E> implements Iterable<E> with add, size, toString and
public Iterator<E> iterator()
returning an object of a private inner class that implements hasNext(), next() and remove():
next()throws aNoSuchElementException("no more elements")at the end;remove()deletes the element returned by the latestnext(), and throws anIllegalStateException("call next() before remove()")if there is none.
main reads integers, then: prints the list; sums it with a for-each loop; removes the even numbers through an iterator; adds 100 at the end; and finally provokes both exceptions. For the input
4 7 10 3 8 8 5
the program prints
List: [4, 7, 10, 3, 8, 8, 5]
Sum with for-each: 45
After removing 4 even number(s): [7, 3, 5], size 3
After adding 100 at the end: [7, 3, 5, 100]
Asking a finished iterator: no more elements
remove() first: call next() before remove()