Java .nextIndex()

StevenSwiniarski's avatar
Published Jun 30, 2022
Contribute to Docs

The .nextIndex() method returns the index of the next element from a ListIterator object. If there is not a next element, it returns the size of the underlying list.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

Syntax

int value = myListIterator.nextIndex();

Where myListIterator is a ListIterator object.

Example

The following example uses a ListIterator to traverse an ArrayList, printing the indices of each item:

import java.util.*;
public class Example {
public static void main(String args[]) {
// Create a new ArrayList
ArrayList l = new ArrayList();
// Add some items to the ArrayList
l.add("A");
l.add("B");
l.add("C");
l.add("D");
l.add("E");
ListIterator i = l.listIterator();
// Loop through ArrayList contents
while(i.hasNext()) {
int index = i.nextIndex();
Object item = i.next();
System.out.println(index + ": " + item);
}
}
}

This example outputs the following:

0: A
1: B
2: C
3: D
4: E

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours