search
HomeJavajavaTutorialA detailed introduction to the Iterator interface and LIstIterator interface in Java

This article mainly introduces the relevant information of java Iteratorinterface and LIstIterator interface analysis. Friends who need it can refer to it

java Iterator interface and LIstIterator interface analysis

Directory

1.Iterator interface
2.ListIterator
3.Iterator and The difference between ListIterator

Text

Before continuing to look at the ArrayList source code, first understand the Iterator interface and the ListIterator interface. The next article will explain ArrayList in detail How to implement them.

We know that the interface is just a specification. When inherits the interface and implements the methods in it, the interface's description of the methods must be followed.

1.Iterator interface

The Iterator interface replaces the Enumeratrion in the Java collection framework . Iterators differ from enumerations in two main ways:

Iterators allow the caller to remove elements from the collection during the iteration process;

The method name has been improved.

Iterator source code is as follows:

/**
 * An iterator over a collection. {@code Iterator} takes the place of
 * {@link Enumeration} in the Java Collections Framework. Iterators
 * differ from enumerations in two ways:
 * Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
 * Method names have been improved.
 * This interface is a member of the Java Collections Framework.
 * @param <E> the type of elements returned by this iterator*/
public interface Iterator<E> {
  /**
   * Returns {@code true} if the iteration has more elements.
   * (In other words, returns {@code true} if {@link #next} would
   * return an element rather than throwing an exception.)
   * @return {@code true} if the iteration has more elements
   */
  boolean hasNext();

  /**
   * Returns the next element in the iteration.
   * @return the next element in the iteration
   * @throws NoSuchElementException if the iteration has no more elements
   */
  E next();

  /**
   * Removes from the underlying collection the last element returned
   * by this iterator (optional operation). This method can be called
   * only once per call to {@link #next}. The behavior of an iterator
   * is unspecified if the underlying collection is modified while the
   * iteration is in progress in any way other than by calling this
   * method.
   *
   * @implSpec
   * The default implementation throws an instance of
   * {@link UnsupportedOperationException} and performs no other action.
   *
   * @throws UnsupportedOperationException if the {@code remove}
   *     operation is not supported by this iterator
   *
   * @throws IllegalStateException if the {@code next} method has not
   *     yet been called, or the {@code remove} method has already
   *     been called after the last call to the {@code next}
   *     method
   */
  default void remove() {
    throw new UnsupportedOperationException("remove");
  }

  /**
   * Performs the given action for each remaining element until all elements
   * have been processed or the action throws an exception. Actions are
   * performed in the order of iteration, if that order is specified.
   * Exceptions thrown by the action are relayed to the caller.
   *
   * @implSpec
   * <p>The default implementation behaves as if:
   * <pre class="brush:php;toolbar:false">{@code
   *   while (hasNext())
   *     action.accept(next());
   * }
   *    * @param action The action to be performed for each element    * @throws NullPointerException if the specified action is null    * @since 1.8    */   default void forEachRemaining(Consumer super E> action) {     Objects.requireNonNull(action);     while (hasNext())       action.accept(next());   } }

The Iterator interface defines four methods and the functions of each method. If a class implements this interface and implements these methods, This method needs to implement the defined functions and follow these rules:

 1).hasNext() determines whether the container has the next element, and returns true if there is;

 2).next() returns The next element in the container;

 3).remove() removes the last element returned by the current iterator. This method can only be called once after each call to the next() method;

 4). Java 8 adds the forEachRemaining method, which can execute the specified function on all remaining elements. operate.

For more detailed instructions, please read the Comments in the source code.

2.ListIterator

ListIterator provides add, set, previous, etc. based on Iterator. Operations on lists. But ListIterator, like Iterator, still operates on the original list.

ListIterator source code is as follows:

/**
 * An iterator for lists that allows the programmer
 * to traverse the list in either direction, modify
 * the list during iteration, and obtain the iterator&#39;s
 * current position in the list. A {@code ListIterator}
 * has no current element; its <I>cursor position</I> always
 * lies between the element that would be returned by a call
 * to {@code previous()} and the element that would be
 * returned by a call to {@code next()}.
 * An iterator for a list of length {@code n} has {@code n+1} possible
 * cursor positions, as illustrated by the carets ({@code ^}) below:
 * <PRE>
 *           Element(0)  Element(1)  Element(2)  ... Element(n-1)
 * cursor positions: ^      ^      ^      ^         ^
 * 
 * Note that the {@link #remove} and {@link #set(Object)} methods are  * not defined in terms of the cursor position; they are defined to  * operate on the last element returned by a call to {@link #next} or  * {@link #previous()}.  *  * This interface is a member of the Java Collections Framework.*/ public interface ListIterator extends Iterator {   // Query Operations   /**    * Returns {@code true} if this list iterator has more elements when    * traversing the list in the forward direction. (In other words,    * returns {@code true} if {@link #next} would return an element rather    * than throwing an exception.)    *    * @return {@code true} if the list iterator has more elements when    *     traversing the list in the forward direction    */   boolean hasNext();   /**    * Returns the next element in the list and advances the cursor position.    * This method may be called repeatedly to iterate through the list,    * or intermixed with calls to {@link #previous} to go back and forth.    * (Note that alternating calls to {@code next} and {@code previous}    * will return the same element repeatedly.)    *    * @return the next element in the list    * @throws NoSuchElementException if the iteration has no next element    */   E next();   /**    * Returns {@code true} if this list iterator has more elements when    * traversing the list in the reverse direction. (In other words,    * returns {@code true} if {@link #previous} would return an element    * rather than throwing an exception.)    *    * @return {@code true} if the list iterator has more elements when    *     traversing the list in the reverse direction    */   boolean hasPrevious();   /**    * Returns the previous element in the list and moves the cursor    * position backwards. This method may be called repeatedly to    * iterate through the list backwards, or intermixed with calls to    * {@link #next} to go back and forth. (Note that alternating calls    * to {@code next} and {@code previous} will return the same    * element repeatedly.)    *    * @return the previous element in the list    * @throws NoSuchElementException if the iteration has no previous    *     element    */   E previous();   /**    * Returns the index of the element that would be returned by a    * subsequent call to {@link #next}. (Returns list size if the list    * iterator is at the end of the list.)    *    * @return the index of the element that would be returned by a    *     subsequent call to {@code next}, or list size if the list    *     iterator is at the end of the list    */   int nextIndex();   /**    * Returns the index of the element that would be returned by a    * subsequent call to {@link #previous}. (Returns -1 if the list    * iterator is at the beginning of the list.)    *    * @return the index of the element that would be returned by a    *     subsequent call to {@code previous}, or -1 if the list    *     iterator is at the beginning of the list    */   int previousIndex();   // Modification Operations   /**    * Removes from the list the last element that was returned by {@link    * #next} or {@link #previous} (optional operation). This call can    * only be made once per call to {@code next} or {@code previous}.    * It can be made only if {@link #add} has not been    * called after the last call to {@code next} or {@code previous}.    *    * @throws UnsupportedOperationException if the {@code remove}    *     operation is not supported by this list iterator    * @throws IllegalStateException if neither {@code next} nor    *     {@code previous} have been called, or {@code remove} or    *     {@code add} have been called after the last call to    *     {@code next} or {@code previous}    */   void remove();   /**    * Replaces the last element returned by {@link #next} or    * {@link #previous} with the specified element (optional operation).    * This call can be made only if neither {@link #remove} nor {@link    * #add} have been called after the last call to {@code next} or    * {@code previous}.    *    * @param e the element with which to replace the last element returned by    *     {@code next} or {@code previous}    * @throws UnsupportedOperationException if the {@code set} operation    *     is not supported by this list iterator    * @throws ClassCastException if the class of the specified element    *     prevents it from being added to this list    * @throws IllegalArgumentException if some aspect of the specified    *     element prevents it from being added to this list    * @throws IllegalStateException if neither {@code next} nor    *     {@code previous} have been called, or {@code remove} or    *     {@code add} have been called after the last call to    *     {@code next} or {@code previous}    */   void set(E e);   /**    * Inserts the specified element into the list (optional operation).    * The element is inserted immediately before the element that    * would be returned by {@link #next}, if any, and after the element    * that would be returned by {@link #previous}, if any. (If the    * list contains no elements, the new element becomes the sole element    * on the list.) The new element is inserted before the implicit    * cursor: a subsequent call to {@code next} would be unaffected, and a    * subsequent call to {@code previous} would return the new element.    * (This call increases by one the value that would be returned by a    * call to {@code nextIndex} or {@code previousIndex}.)    *    * @param e the element to insert    * @throws UnsupportedOperationException if the {@code add} method is    *     not supported by this list iterator    * @throws ClassCastException if the class of the specified element    *     prevents it from being added to this list    * @throws IllegalArgumentException if some aspect of this element    *     prevents it from being added to this list    */   void add(E e); }

The function of ListIterator is more powerful, and the defined methods are:

 1).hasNext() when traversing forward , returns true if there is a next element;

 2).next() returns the value of the next element and adds 1 to the pointer;

 3).hasPrevious() traverses in the opposite direction If there are still elements, return true;

 4).previous() Returns the value of the previous element and moves the pointer forward by 1;

 5).nextIndex() Returns this time The index of the element returned when the next() method is called;

6).previousIndex() returns the index of the element returned when the previous() method is called;

 7).remove() Removes the element returned by the most recent call to next() or previous() method (optional);

 8).set(E e) Use element e to set if it is called at this time The element returned by the next() or previous() method is replaced;

 9).add(E e) Adds an element before the element returned by calling next() at this time, or returns by calling previous() at this time after the element.

For more detailed instructions, please read the comments in the source code.

3. The difference between Iterator and ListIterator

The method comparison between Iterator and ListIterator is as follows:

hasNext()Overridenext()Overwriteremove()OverwriteforEachRemaining(Consumer super E> action)InheritancehasPrevious()previous()nextIndex()
Iterator

ListIterator

hasNext()

next()

remove()

forEachRemaining(Consumer super E> action)

##previousIndex()
set(E e)
add(E e)
The main differences between the two are:

 1).Iterator can only be one-way Move, ListIterator can move in both directions;

 2).ListIterator can

delete

, replace or add elements, while Iterator can only delete elements; 3).ListIterator can return The index of the current element (returned by calling next() or previous()), but Iterator cannot.

The above is the detailed content of A detailed introduction to the Iterator interface and LIstIterator interface in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software