
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Obtain Previous and Next Index in ArrayList Using ListIterator in Java
The previous index and next index in an ArrayList can be obtained using the methods previousIndex() and nextIndex() respectively in the ListIterator Interface.
The previousIndex() method returns the index of the element that is returned by the previous() method while the nextIndex() method returns the index of the element that is returned by the next() method. Neither of these methods require any parameters.
A program that demonstrates this is given as follows
Example
import java.util.ArrayList; import java.util.ListIterator; public class Demo { public static void main(String[] args) { ArrayList<String> aList = new ArrayList<String>(); aList.add("Amy"); aList.add("Peter"); aList.add("Justin"); aList.add("Emma"); aList.add("James"); System.out.println("The ArrayList elements are: "+ aList); ListIterator<String> li = aList.listIterator(); System.out.println("The previous index is: " + li.previousIndex()); System.out.println("The next index is: " + li.nextIndex()); } }
Output
The output of the above program is as follows
The ArrayList elements are: [Amy, Peter, Justin, Emma, James] The previous index is: -1 The next index is: 0
Now let us understand the above program.
The ArrayList is created and ArrayList.add() is used to add the elements to the ArrayList. Then the ArrayList elements are displayed. The previous index and next index in an is obtained using the methods previousIndex() and nextIndex() respectively. A code snippet which demonstrates this is as follows
ArrayList<String> aList = new ArrayList<String>(); aList.add("Amy"); aList.add("Peter"); aList.add("Justin"); aList.add("Emma"); aList.add("James"); System.out.println("The ArrayList elements are: "+ aList); ListIterator<String> li = aList.listIterator(); System.out.println("The previous index is: " + li.previousIndex()); System.out.println("The next index is: " + li.nextIndex());