Iterator Interface
You will eventually implement your own iterator for your own lists. Your iterator will implement the standard Iterator interface. Let’s discuss each method and its expected behavior. Some of the expected behavior of your iterator will differ slightly from the standard implementation, so read these descriptions carefully.
hasNext
boolean hasNext()
Returns true if the iteration has more elements. (In other words, returns true if next() would return an element rather than throwing an exception.)
Throws:
ConcurrentModificationException – if the list has been modified outside of this iterator
This method will need to check if there are elements remaining in the list. It should return true if there are and return false if no more elements are left. It should throw a ConcurrentModificationException if the list is modified if the list has been modified in any way by anything other than this iterator.
next
E next()
Returns the next element in the iteration.
Throws:
NoSuchElementException– if the iteration has no more elements
ConcurrentModificationException – if the list has been modified outside of this iterator
This method will return the next element in the list or throw an exception if there aren’t any elements left (i.e. if hasNext() returns false). It should throw a ConcurrentModificationException if the list is modified if the list has been modified in any way by anything other than this iterator.
remove
void remove()
Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next().
Throws:
IllegalStateException – if the next method has not yet been called, or the remove method has already been called after the last call to the next method
ConcurrentModificationException – if the list has been modified outside of this iterator
This method should return the element that was most recently returned by a call to next. It does not remove the next element in the list; it does not allow you to find an element to remove. Whatever was returned by next is what gets removed. That’s why it doesn’t need to return anything. The user must call next before they can call remove. The user can call remove exactly once per call to next. In other words, the user is not allowed to call remove twice in a row.
It should throw a ConcurrentModificationException if the list is modified if the list has been modified in any way by anything other than this iterator. Note that remove is the only iterator method that modifies the list. It is perfectly fine to have multiple iterators moving through the same list, as long as they only call hasNext() and/or next(). Those methods do not modify the list. If one iterator calls remove, however, that invalidates all other iterators.