search
HomeJavajavaTutorialDetailed explanation and analysis of ListIterator and Iterator in Java

When using java collections, you need to use Iterator. But there is also an iterator ListIterator in the java collection, which can be used when using List, ArrayList, LinkedList and Vector. What is the difference between these two iterators? Let’s analyze it in detail below. One thing that needs to be made clear here is that the position pointed by the iterator is the position before the element, as shown in the following figure:

Detailed explanation and analysis of ListIterator and Iterator in Java

Here it is assumed that the collection List consists of four elements List1, List2, List3 and List4. When using the statement Iterator When it = List.Iterator(), the position pointed by the iterator it is the position pointed by Iterator1 in the above figure. After the statement it.next() is executed, the position pointed by the iterator moves to the position pointed by Iterator2 in the above figure.

First, let’s take a look at the methods of Iterator and ListIterator.

Iterator contains the following methods:

hasNext(): If there is an element after the position pointed by the iterator, return true, otherwise return false

next(): Return the element after the position pointed by the Iterator in the set

remove(): Delete the element in the collection after the position pointed by the Iterator. The methods included in the ListIterator are:

add(E e): Insert the specified element into the list, and the insertion position is before the current position of the iterator.

hasNext( ): When traversing the list in the forward direction, if there are elements after the list iterator, it returns true, otherwise it returns false

hasPrevious(): If it traverses the list in the reverse direction, and there are elements in front of the list iterator, it returns true, otherwise Returns false

next(): Returns the element in the list after the position pointed by ListIterator

nextIndex(): Returns the index of the element after the position required by ListIterator in the list

previous(): Returns the element in the list before the position pointed by ListIterator

previousIndex(): Returns the index of the element in front of the desired position of ListIterator in the list

remove(): Removes the last element returned by next() or previous() from the list (a bit confusing, it means using hasNext() on the iterator ) method, delete the element after the position pointed by ListIterator; when using the hasPrevious() method on the iterator, delete the element before the position pointed by ListIterator)

set(E e): Remove next() or previous() from the list The last element returned The last element returned is changed to the specified element e

one. The same thing

are iterators. When you need to traverse the elements in the collection without interfering with the traversal process, both iterators can be used.

2. Differences

1. Different usage scope, Iterator can be applied to all collections, Set, List and Map and subtypes of these collections. ListIterator can only be used for List and its subtypes.

2. ListIterator has an add method, which can add objects to the List, but Iterator cannot.

3. Both ListIterator and Iterator have hasNext() and next() methods, which can realize sequential backward traversal, but ListIterator has hasPrevious() and previous() methods, which can realize reverse (sequential forward) traversal. Iterator cannot.

4.ListIterator can locate the position of the current index, and nextIndex() and previousIndex() can achieve this. Iterator does not have this functionality.

5. Both can implement deletion operations, but ListIterator can implement object modification, and the set() method can achieve it. Iterator can only be traversed and cannot be modified.

Three: Iterator and ListIterator usage examples

ListIterator usage:

package com.collection;

import java.util.LinkedList;

import java.util.List;

import java.util.ListIterator;

public class ListIteratorTest {
 public static void main(String[] args) {  // TODO Auto-generated method stub  List<String> staff = new LinkedList<>();  staff.add("zhuwei");  staff.add("xuezhangbin");  staff.add("taozhiwei");  ListIterator<String> iter = staff.listIterator();  String first = iter.next();    //删除zhuwei  iter.remove();    //把zhuwei改为simei  //iter.set("simei");  System.out.println("first:"+first);    iter.add("xiaobai");    //遍历List元素  System.out.println("遍历List中元素,方法一:");  for(String str : staff)   System.out.println(str+"  ");    iter = staff.listIterator();  System.out.println("遍历List中元素,方法二:");  while(iter.hasNext())  {   System.out.println(iter.next());  } }
}

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 do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor