Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

listIterator()

Example

Utilize a ListIterator to iterate both forward and backward through a list.

import java.util.ArrayList;
import java.util.ListIterator;
public class Main {
  public static void main(String[] args) {
    // Make a collection
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    // Get the iterator
   listIterator<String> it = cars.listiterator();
    // Loop through the list
    while(it.hasNext()) {
      System.out.println(it.next());
    }

 
   System.out.println("---");
    // Loop backwards through the list
    while(it.hasPrevious()) {
     
System.out.println(it.previous());
    }
  }
}

Definition and Usage

The listIterator() method provides a ListIterator for the list.

For guidance on iterators, refer to our Java Iterator tutorial.

Unlike an Iterator, a ListIterator can traverse the list both forwards and backwards.

Syntax

public ListIterator listIterator()

Technical Details

Returns:

An object of ListIterator.