Class IndexTrackingIterator<T>
- Type Parameters:
T- the type of elements in the list
- All Implemented Interfaces:
Iterator<T>, ListIterator<T>
This iterator wraps a standard ListIterator and maintains
the index of the most recently read element, which can be accessed via
currentIndex().
This class provides a generic implementation that can be used with any type of list elements. It correctly handles bidirectional iteration by tracking the current index internally.
This iterator is particularly useful for operations that need to know the position of elements during iteration, such as calculating correspondences between lists or tracking modifications.
- Since:
- 3.28.0
-
Constructor Summary
ConstructorsConstructorDescriptionIndexTrackingIterator(List<T> elements) Creates an iterator starting at the beginning of the list.IndexTrackingIterator(List<T> elements, int fromIndex) Creates an iterator starting at the specified index. -
Method Summary
Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface Iterator
forEachRemaining
-
Constructor Details
-
IndexTrackingIterator
-
IndexTrackingIterator
Creates an iterator starting at the specified index. The current index is initialized to -1, indicating that no element has been read yet.- Parameters:
elements- the list to iterate overfromIndex- the starting index (cursor position)- Throws:
IndexOutOfBoundsException- if fromIndex is out of range
-
-
Method Details
-
currentIndex
public int currentIndex()Returns the index of the element that was returned by the most recent call tonext()orprevious().This method can be called multiple times without side effects - it will always return the same value until the next call to
next(),previous(), orremove().Important: If neither
next()norprevious()has been called yet, or ifremove()was called after the last call tonext()orprevious(), this method returns -1.Note: In the legacy
ArrayIteratorclass, this method was namedindex(). It has been renamed tocurrentIndex()for better clarity and consistency.- Returns:
- the index of the current element, or -1 if no element has been read or the current element was removed
-
hasNext
-
next
-
hasPrevious
public boolean hasPrevious()- Specified by:
hasPreviousin interfaceListIterator<T>
-
previous
- Specified by:
previousin interfaceListIterator<T>
-
nextIndex
public int nextIndex()- Specified by:
nextIndexin interfaceListIterator<T>
-
previousIndex
public int previousIndex()- Specified by:
previousIndexin interfaceListIterator<T>
-
remove
-
set
- Specified by:
setin interfaceListIterator<T>
-
add
- Specified by:
addin interfaceListIterator<T>
-