- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to get previous and next index using ListIterator
To get the exact evaluation of the previous and next index, you need use the next() method of the Iterator. This will eventually help you in gaining more understanding about Iterators. Let us first create an ArrayList and add some elements −
ArrayList <Integer> arrList = new ArrayList <Integer> (); arrList.add(100); arrList.add(200); arrList.add(300); arrList.add(400); arrList.add(500); arrList.add(600); arrList.add(700); arrList.add(800); arrList.add(900); arrList.add(1000);
Now, create a ListIterator −
ListIterator<Integer>iterator = arrList.listIterator();
Get the previous and next index now −
iterator.previousIndex(); iterator.nextIndex();
Example
import java.util.ArrayList; import java.util.ListIterator; public class Demo { public static void main(String[] args) { ArrayList<Integer>arrList = new ArrayList<Integer>(); arrList.add(100); arrList.add(200); arrList.add(300); arrList.add(400); arrList.add(500); arrList.add(600); arrList.add(700); arrList.add(800); arrList.add(900); arrList.add(1000); System.out.println("ArrayList..."); for (Integer i: arrList) System.out.println(i); ListIterator<Integer>iterator = arrList.listIterator(); System.out.println("Previous Index =" + iterator.previousIndex()); System.out.println("Next Index = " + iterator.nextIndex()); iterator.next(); System.out.println("Previous Index = " + iterator.previousIndex()); System.out.println("Next Index =" + iterator.nextIndex()); iterator.next(); iterator.next(); System.out.println("Previous Index = " + iterator.previousIndex()); System.out.println("Next Index = " + iterator.nextIndex()); } }
Output
ArrayList... 100 200 300 400 500 600 700 800 900 1000 Previous Index =-1 Next Index = 0 Previous Index = 0 Next Index =1 Previous Index = 2 Next Index = 3
Advertisements
To Continue Learning Please Login
Login with Google