📜  Java中的 Stack remove(int) 方法与示例

📅  最后修改于: 2022-05-13 01:55:23.765000             🧑  作者: Mango

Java中的 Stack remove(int) 方法与示例

Java.util.Stack.remove( int index )方法用于从特定位置或索引的堆栈中删除元素。

句法:

Stack.remove(int index)

参数:此方法接受强制参数索引是整数数据类型,并指定要从堆栈中删除的元素的位置。

返回值:此方法返回刚刚从堆栈中删除的元素

下面的程序说明了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 stack = new Stack();
  
        // 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 stack = new Stack();
  
        // 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]