Java LinkedList listIterator() Method

Java LinkedList Java LinkedList


listIterator()The method is an important method in JavaLinkedListprovided by the class, it returns aListIteratorobject, used to traverse the elements in the linked list. Compared with the ordinaryIteratorcompared with,ListIteratorit provides richer operation functions.

Method Syntax

public ListIterator<E> listIterator()
public ListIterator<E> listIterator(int index)
  • No-arg version: returns a list iterator starting from the beginning of the linked list
  • Parameterized version: returns a list iterator starting from the specified index position

Method Parameters

index parameter

  • Type:int
  • Meaning: the position index where the iterator starts
  • Value range:0 <= index <= size()
  • If the passed index equals the linked list size (size()), the iterator will point to the end of the linked list

Return Value

Returns aListIteratorobject, which provides the ability to traverse the linked list bidirectionally.


Main Methods of ListIterator

Traversal Methods

  • boolean hasNext(): Checks whether there is a next element
  • E next(): Returns the next element and moves the cursor forward
  • boolean hasPrevious(): Checks whether there is a previous element
  • E previous(): Returns the previous element and moves the cursor backward

Modification Methods

  • void add(E e): Inserts an element at the current position
  • void remove(): Removes the last element returned by callingnext()orprevious()the element returned by
  • void set(E e): Replaces the last element returned by callingnext()orprevious()the element returned by

Usage Examples

Basic Traversal Example

Example

import java.util.LinkedList;
import java.util.ListIterator;

public class Main {
    public static void main(String[] args) {
        LinkedList<String> fruits = new LinkedList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
       
        // Get ListIterator
        ListIterator<String> iterator = fruits.listIterator();
       
        // Forward traversal
        System.out.println("Forward traversal:");
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }
       
        // Reverse traversal
        System.out.println("\n"Reverse traversal:");
        while(iterator.hasPrevious()) {
            System.out.println(iterator.previous());
        }
    }
}

Traversing from a Specified Position

Example

ListIterator<String> iterator = fruits.listIterator(1);  // Start from index 1
System.out.println("Traversing from index 1:");
while(iterator.hasNext()) {
    System.out.println(iterator.next());
}

Modifying Linked List Content

Example

ListIterator<String> iterator = fruits.listIterator();
iterator.next();  // Move to the first element
iterator.set("Apricot");  // Modify the first element
iterator.add("Blueberry");  // Add a new element at the current position

System.out.println("Modified linked list:");
for(String fruit : fruits) {
    System.out.println(fruit);
}

Notes

  1. Concurrent modification: If the linked list is modified by other means during iteration (rather than through the iterator's own methods), aConcurrentModificationExceptionexception will be thrown.

  2. Initial position: A newly createdListIteratorhas its cursor initially positioned before the first element (for the no-arg version) or before the specified index position (for the parameterized version).

  3. Boundary check: Callingnext()orprevious()when there is no corresponding element, aNoSuchElementException。

  4. Modification operation restrictions: Before callingadd()、remove()orset()you must first callnext()orprevious(), otherwise aIllegalStateException。


Differences from Iterator

Feature Iterator ListIterator
Traversal direction One-way (forward only) Two-way (forward and backward)
Modification methods Only remove() add(), remove(), set()
Get index Not supported Supports nextIndex() and previousIndex()
Creation method iterator() listIterator()

Performance Considerations

  • LinkedListoflistIterator()The method has a time complexity of O(1), because it simply creates a new iterator object.
  • The various operations of the iterator itself (such asnext()、previous()) have a time complexity of O(1), becauseLinkedListit is implemented based on a doubly linked list.
  • For scenarios that require frequent insertion or deletion in the middle of the list, usingListIteratoris more efficient than operating directly through indices.

Summary

LinkedListoflistIterator()The method provides more powerful functionality than a regular iterator, especially suitable for scenarios where you need to modify the linked list content during traversal or need bidirectional traversal. Understanding and skillfully using this method allows you to operate more efficiently onLinkedList。

Java LinkedList Java LinkedList

Other Extensions