Java Stack remove(int)方法与实例
Java.util.Stack .remove( int index )方法用于从Stack的一个特定位置或索引中删除一个元素。
语法
Stack.remove(int index)
参数: 该方法接受一个强制性参数index,该参数为整数数据类型,指定要从Stack中删除的元素的位置。
返回值: 该方法返回刚刚从堆栈中删除的元素 。
下面的程序说明了Java.util.Stack.remove(int index)方法。
例1.删除
// Java code to illustrate remove() when position of
// element is passed as parameter
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<String> stack = new Stack<String>();
// Use add() method to add elements in the Stack
stack.add("Geeks");
stack.add("for");
stack.add("Geeks");
stack.add("10");
stack.add("20");
// Output the Stack
System.out.println("Stack: " + stack);
// Remove the element using remove()
String rem_ele = stack.remove(4);
// Print the removed element
System.out.println("Removed element: "
+ rem_ele);
// Print the final Stack
System.out.println("Final Stack: "
+ stack);
}
}
输出:
Stack: [Geeks, for, Geeks, 10, 20]
Removed element: 20
Final Stack: [Geeks, for, Geeks, 10]
例2:
// Java code to illustrate remove() when position of
// element is passed as parameter
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<Integer> stack = new Stack<Integer>();
// Use add() method to add elements in the Stack
stack.add(10);
stack.add(20);
stack.add(30);
stack.add(40);
stack.add(50);
// Output the Stack
System.out.println("Stack: " + stack);
// Remove the element using remove()
int rem_ele = stack.remove(0);
// Print the removed element
System.out.println("Removed element: "
+ rem_ele);
// Print the final Stack
System.out.println("Final Stack: "
+ stack);
}
}
输出:
Stack: [10, 20, 30, 40, 50]
Removed element: 10
Final Stack: [20, 30, 40, 50]
极客教程