Typically, you would want to iterate through the elements in a collection. For example, displays each element in the collection. The general traversal array is either a for loop or an enhanced for, and these two methods can also be used in the collection framework, but there is also a way to iterate through the collection framework, which is an object that implements the iterator interface or the Listiterator interface. An iterator that enables you to iterate through the elements of the collection or delete them. Listiterator inherits the iterator to allow bidirectional traversal of the list and modify the elements. Iterator and Listiterator are generic interfaces, and their declarations are:
Interface iterator<e>
Interface listiterator<e>
Methods for iterator interface declarations
default void Foreachremaining (CONSUMER<? Super e> Action) |
Performs action-specified actions for each unhandled element in the collection (JDK8 new) |
Boolean Hasnext () |
Returns true if there are more elements, otherwise false |
E Next () |
Returns the next element. Throws a Nosuchelementexception exception if no next element exists |
default void Remove () |
Removes the current element. If you try to call remove () before calling the next () method, an exception is thrown |
methods for Listiterator interface declarations
Method |
Describe |
void Add (E obj) |
Inserts obj into the list, and the newly inserted element precedes the next next () method call returned by the element |
Boolean Hasnext () |
Returns true if the next element is present, otherwise it returns false |
Boolean hasprevious () |
Returns true if the previous element is present, otherwise false |
E Next () |
Returns the next element. Throws a Nosuchelementexception exception if no next element exists |
int Nextindex () |
Returns the index of the next element. Returns the size of the list if no next element exists |
E Previous () |
Returns a previous element. Throws a Nosuchelementexception exception if the previous element does not exist |
int Previousindex () |
Returns the index of the previous element. Returns 1 if no previous element exists |
void Remove () |
Removes the current element from the list. If the Remove () method is called before the next () or previous () method is called, the IllegalStateException exception is thrown |
void set (E obj) |
Assigns the value of obj to the current element, which is the last element returned by the next () or previous () method call |
Only a collection that implements the list interface can use Listiterator.
The iterator--ITERATORJK and Listitertor interface for the Java Learning Collection framework