An online markdown blog and knowledge repository.
Iterators are functions that can loop through a collection of some type.
A cursor is a placeholder that always lies between items in a collection of some type.
The Cursor concept is exposed via java.util Interface Iterator<E>
.
The interface is found within the Java Collections Framework.
E => The type of elements returned by this iterator.
A collection with n elements has n+1 cursor positions.
Cursor can return:
Cursor can also:
Bottom Line: Consider the cursor an ephemeral pointer used to placehold between elements of a collection, and as a demarcating tool when it is at the beginning (-1) or the end (length) of a collection.
The following Iterfaces utilize Cursor to perform naviation and operations on collections.
List Iterator makes use of Cursor to navigate, insert into, and remove from, the collection.
It's Superinterface is Iterator<E>
(detailed below).
Methods:
Restrictions on using remove():
Restricutions on using set(E):
Restrictions on using add(E):
cursor
is between previous() and next()).remove() Throws:
set() Throws:
add() Throws:
E: The type of element returned by the iterator.
This is a parent interface to subinterface ListIterator<E>
.
Scanner
class implements this interface.
Iterator is a forward-navigating interface. ListIterator has additional functionality based on this one.
hasNext(): Returns boolean.
next(): Returns next Element in the iteration. Throws NoSuchElementException.
remove(): Returns Element on a conditional basis (see below). Throws (see below).
Conditions of remove():
next()
must have been called prior to calling remove().next()
call is removed from the collection.next()
.remove() throws:
next()
has not been called, or remove()
has already been called since the last next()
call.Enumerations are used to retrieve elements from a collection or specify input streams to SequenceInputStream.
Create an enumeration on a collection by calling elements()
on it.
Utilize method nextElement()
to move the enumeration pointer forward through the collection once per call.
Enumeration<String> enumeration = myCollection.elements();
while(enumeration.hasMoreElements()) {
// do stuff
enumeration.nextElement();
}
Iterators enable retrieving elements one-by-one.
Read and Remove operations are supported.
Are universal and can be applied to all collections.
Create one by calling iterator()
method in any collection.
// create a myList collection and then...
Iterator<String> itML = myList.iterator();
while (itML.hasNext()) {
// iterate using next
if (itML.next() == 'some value') {
// remove the current element
itML.remove();
}
}
ListIterator<E> allows iterating in both directions (forward and backward) as explained earlier in this document.
Oracle Docs java.util Interface ListIterator.
Oracle Docs java.util Iterator<E>.
Oracle Docs Java Collections Framework.
Baeldung blog post on Iterator and Enumerator.
Back to ContEd Index
Back to Root README