Java .previousIndex()
Published Jun 30, 2022
Contribute to Docs
The .previousIndex() method returns the index of the previous element from a ListIterator object. If there is not a previous element, it returns -1.
Syntax
int value = myListIterator.previousIndex();
Where myListIterator is a ListIterator object.
Example
The following example uses a ListIterator to traverse an ArrayList and then traverse it back in the opposite direction, printing the indices of each item:
import java.util.*;public class Example {public static void main(String args[]) {// Create a new ArrayListArrayList l = new ArrayList();// Add some items to the ArrayListl.add("A");l.add("B");l.add("C");l.add("D");l.add("E");ListIterator i = l.listIterator();// Loop through ArrayList contentswhile(i.hasNext()) {int index = i.nextIndex();Object item = i.next();System.out.println(index + ": " + item);}// Loop back through ArrayList contentswhile(i.hasPrevious()) {int index = i.previousIndex();Object item = i.previous();System.out.println(index + ": " + item);}}}
This example outputs the following:
0: A1: B2: C3: D4: E4: E3: D2: C1: B0: A
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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