The listIterator() method of Java.util.Stack class is used to return a list iterator over the elements in this stack (in proper sequence). The returned list iterator is fail-fast.
Syntax:
public ListIterator listIterator()
Return Value: This method returns a list iterator over the elements in this stack (in proper sequence).
Below are the examples to illustrate the listIterator() method.
Example 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
Stack<String>
stack = new Stack<String>();
stack.add( "A" );
stack.add( "B" );
stack.add( "C" );
stack.add( "D" );
System.out.println( "Stack: "
+ stack);
ListIterator<String>
iterator = stack.listIterator();
System.out.println( "\nUsing ListIterator:\n" );
while (iterator.hasNext()) {
System.out.println( "Value is : "
+ iterator.next());
}
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Stack: [A, B, C, D]
Using ListIterator:
Value is : A
Value is : B
Value is : C
Value is : D
Program 2:
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
Stack<Integer> stack = new Stack<Integer>();
stack.add( 1 );
stack.add( 2 );
stack.add( 3 );
stack.add( 10 );
stack.add( 20 );
System.out.println( "Stack: " + stack);
ListIterator<Integer>
iterator = stack.listIterator();
System.out.println( "\nUsing ListIterator:\n" );
while (iterator.hasNext()) {
System.out.println( "Value is : "
+ iterator.next());
}
}
}
|
Output:
Stack: [1, 2, 3, 10, 20]
Using ListIterator:
Value is : 1
Value is : 2
Value is : 3
Value is : 10
Value is : 20
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
24 Dec, 2018
Like Article
Save Article