Hello everyone, here I have sharing my knowledge of What is the difference between Iterator and ListIterator in Java?. please find the below points and sample program.
1. ListIterator class allows the developers to iterate only the list object in both directions such as forward and backward direction using previous() and next() method. whereas Iterator class can be used to iterate the list, set and map object in one direction such as forward.
2. ListIterator is updatable during iteration using add(), and remove(). But Iterator can not add the element during iteration but they can remove the element from collection object during the iteration as they only consist of remove() method. There is no add() method in Iterator.
3. We can get the current position of object, during execution by using previousIndex() & nextIndex() methods in ListIterator class. But during iteration current position can not be identified using Iterator class.
IteratorsExample.java
package com.javatraineronline.example; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class IteratorsExample { public static void main(String[] args) { List<String> strList = new ArrayList<String>(); strList.add("A"); strList.add("B"); strList.add("C"); strList.add("D"); strList.add("E"); // Defining Iterator Object Iterator<String> iterator = strList.iterator(); System.out.println("---------------------------------------"); System.out.println("Iterator"); System.out.println("---------------------------------------"); System.out.println("Iterating elements using Iterator Class -> Forward Iteration"); while(iterator.hasNext()) { System.out.print(iterator.next()+" "); // Forward Iteration } System.out.println("\n---------------------------------------"); System.out.println("ListIterator"); System.out.println("---------------------------------------"); ListIterator<String> list = strList.listIterator(); System.out.println("Iterating elements using ListIterator -> Forward & Backward Iteration"); while(list.hasNext()) { System.out.print(list.next()+" "); } System.out.println(); while(list.hasPrevious()) { System.out.print(list.previous()+" "); } } }
Output
[su_box title=”Output for RepeatNumberCount.java”]—————————————
Iterator
—————————————
Iterating elements using Iterator Class -> Forward Iteration
A B C D E
—————————————
ListIterator
—————————————
Iterating elements using ListIterator -> Forward & Backward Iteration
A B C D E
E D C B A [/su_box]
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
One response
Gee wiliskerl, that’s such a great post!