The Methods Defined by ListIterator in java

Table of The Methods Defined by ListIterator

MethodDescription
void add(E obj)Inserts obj into the list in front of the element that will be returned
 by the next call to next( ).
  
boolean hasNext( )Returns true if there is a next element. Otherwise, returns false.
  
boolean hasPrevious( )Returns true if there is a previous element. Otherwise, returns false.
  
E next( )Returns the next element. A NoSuchElementException is thrown
 if there is not a next element.
int nextIndex( )Returns the index of the next element. If there is not a next element,
 returns the size of the list.
E previous( )Returns the previous element. A NoSuchElementException is thrown
 if there is not a previous element.
  
int previousIndex( )Returns the index of the previous element. If there is not a previous
 element, returns −1.
  
void remove( )Removes the current element from the list. An IllegalStateException
 is thrown if remove( ) is called before next( ) or previous( ) is invoked.
  
void set(E obj)Assigns obj to the current element. This is the element last returned
 by a call to either next( ) or previous( ).

Demonstrate iterators

import java.util.*;

class IteratorDemo {

public static void main(String args[]) { // Create an array list.

ArrayList<String> al = new ArrayList<String>();

//Add elements to the array list. al.add("C");

al.add("A");

al.add("E");

al.add("B");

al.add("D");

al.add("F");

//Use iterator to display contents of al. System.out.print("Original contents of al: "); Iterator<String> itr = al.iterator(); while(itr.hasNext()) {

String element = itr.next(); System.out.print(element + " ");

}

System.out.println();

//Modify objects being iterated. ListIterator<String> litr = al.listIterator(); while(litr.hasNext()) {

String element = litr.next(); litr.set(element + "+");

}

System.out.print("Modified contents of al: "); itr = al.iterator(); while(itr.hasNext()) {
String element = itr.next(); System.out.print(element + " ");

}

System.out.println();

//Now, display the list backwards. System.out.print("Modified list backwards: "); while(litr.hasPrevious()) {

String element = litr.previous(); System.out.print(element + " ");

}

System.out.println();

}

}
Original contents of al: C A E B D F

Modified contents of al: C+ A+ E+ B+ D+ F+

Modified list backwards: F+ D+ B+ E+ A+ C+

Leave a Comment