


A 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'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
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
Iterator | ListIterator | |
hasNext() | hasNext()Override | |
next() | next()Overwrite | |
remove() | remove()Overwrite | |
forEachRemaining(Consumer super E> action) | forEachRemaining(Consumer super E> action)Inheritance | |
hasPrevious() | ||
previous() | ||
nextIndex() | ||
##previousIndex() | ||
set(E e) | ||
add(E e) |
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
