What is difference between Iterator and ListIterator

What is difference between Iterator and ListIterator

Answer :

IteratorListIterator
Moves forward onlyMoves both direction (backward and forward)
iterate through List, Set and Mapiterate only List
Cannot modify during iterationCan modify list during iteration
Cannot obtain current position of iteratorCan obtain iterator current position
Cannot add value during iterationCan add value at any point
Cannot set value at that pointCan 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:

What is difference between Iterator and ListIterator

 

Leave a Reply

Your email address will not be published. Required fields are marked *