The Java.util.Stack.remove(int index) method is used to remove an element from a Stack from a specific position or index.
Syntax:
Stack.remove(int index)
Parameters: This method accepts a mandatory parameter index is of integer data type and specifies the position of the element to be removed from the Stack.
Return Value: This method returns the element that has just been removed from the Stack.
Below program illustrate the Java.util.Stack.remove(int index) method:
Example 1:
import java.util.*;
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);
String rem_ele = stack.remove( 4 );
System.out.println( "Removed element: "
+ rem_ele);
System.out.println( "Final Stack: "
+ stack);
}
}
|
Output:
Stack: [Geeks, for, Geeks, 10, 20]
Removed element: 20
Final Stack: [Geeks, for, Geeks, 10]
Example 2:
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
Stack<Integer> stack = new Stack<Integer>();
stack.add( 10 );
stack.add( 20 );
stack.add( 30 );
stack.add( 40 );
stack.add( 50 );
System.out.println( "Stack: " + stack);
int rem_ele = stack.remove( 0 );
System.out.println( "Removed element: "
+ rem_ele);
System.out.println( "Final Stack: "
+ stack);
}
}
|
Output:
Stack: [10, 20, 30, 40, 50]
Removed element: 10
Final Stack: [20, 30, 40, 50]
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