What is difference between Iterator and ListIterator
Answer :
Iterator | ListIterator |
Moves forward only | Moves both direction (backward and forward) |
iterate through List, Set and Map | iterate only List |
Cannot modify during iteration | Can modify list during iteration |
Cannot obtain current position of iterator | Can obtain iterator current position |
Cannot add value during iteration | Can add value at any point |
Cannot set value at that point | Can set value at that point (Replaces the last element returned by next or previous with the specified element (optional operation). This call can be made only if neither remove nor add have been called after the last call to next or previous.) |
Please see example below:
package com.javahonk.iteratortest; import java.util.ArrayList; import java.util.Iterator; import java.util.ListIterator; public class ListIteratorTest { public static void main(String[] args) { ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("J"); arrayList.add("A"); arrayList.add("V"); arrayList.add("A"); arrayList.add("H"); arrayList.add("O"); arrayList.add("N"); arrayList.add("K"); System.out.print("Original contents of arrayList : "); Iterator<String> itr = arrayList.iterator(); while (itr.hasNext()) { String element = itr.next(); System.out.print(element + " "); } System.out.println(); // Modify the objects during iteration ListIterator<String> litr = arrayList.listIterator(); while (litr.hasNext()) { String element = litr.next(); litr.set(element + "+"); } System.out.print("Modified contents of arrayList : "); itr = arrayList.iterator(); while (itr.hasNext()) { String element = itr.next(); System.out.print(element + " "); } System.out.println(); // Display the list backwards. System.out.print("Modified list backwards: "); while (litr.hasPrevious()) { String element = litr.previous(); System.out.print(element + " "); } System.out.println(); } }
Output: