
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
Use ListIterator to Traverse an ArrayList in Forward Direction in Java
A ListIterator can be used to traverse the elements in the forward direction as well as the reverse direction in the List Collection. So the ListIterator is only valid for classes such as LinkedList, ArrayList etc.
The method hasNext( ) in ListIterator returns true if there are more elements in the List and false otherwise. The method next( ) returns the next element in the List and advances the cursor position.
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("Amanda"); aList.add("Peter"); aList.add("Julie"); aList.add("James"); aList.add("Emma"); ListIterator li = aList.listIterator(); System.out.println("The ArrayList elements in the forward direction are: "); while (li.hasNext()) { System.out.println(li.next()); } } }
Output
The ArrayList elements in the forward direction are: Amanda Peter Julie James Emma
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 in the forward direction using an iterator which makes use of the ListIterator interface. A code snippet which demonstrates this is as follows −
ArrayList<String> aList = new ArrayList<String>(); aList.add("Amanda"); aList.add("Peter"); aList.add("Julie"); aList.add("James"); aList.add("Emma"); ListIterator li = aList.listIterator(); System.out.println("The ArrayList elements are: "); while (li.hasNext()) { System.out.println(li.next()); }