Stack elementAt() method in Java with Example
The Java.util.Stack.elementAt(int pos) method is used to fetch or retrieve an element at a specific index from a Stack.
Syntax:
Stack.elementAt(int pos)
Parameters: This method accepts a mandatory parameter pos of integer data type that specifies the position or index of the element to be fetched from the Stack.
Return Value: The method returns the element present at the position specified by the parameter pos.
Below programs illustrate the Java.util.Stack.get() method:
Program 1:
import java.util.Stack;
public class StackDemo {
public static void main(String args[])
{
Stack<String> stack = new Stack<String>();
stack.add( "Geeks" );
stack.add( "for" );
stack.add( "Geeks" );
stack.add( "10" );
stack.add( "20" );
System.out.println( "Stack: "
+ stack);
System.out.println( "The element is: "
+ stack.elementAt( 3 ));
}
}
|
Output:
Stack: [Geeks, for, Geeks, 10, 20]
The element is: 10
Program 2:
import java.util.Stack;
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( 4 );
stack.add( 5 );
System.out.println( "Stack: " + stack);
System.out.println( "The element is: "
+ stack.elementAt( 1 ));
}
}
|
Output:
Stack: [1, 2, 3, 4, 5]
The element is: 2
Last Updated :
24 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...