📜  Java中的堆栈 removeElementAt() 方法与示例

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

Java中的堆栈 removeElementAt() 方法与示例

Java.util.Stack.removeElementAt(int index)方法用于从特定位置或索引的堆栈中删除元素。在这个过程中,堆栈的大小会自动减少一个,并且在删除的元素之后的所有其他元素都向下移动一个位置。

句法:

Stack.removeElementAt(int index)

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

返回值:此方法具有void返回类型。这意味着它不返回任何东西。

下面的程序说明了Java.util.Stack.remove(int index) 方法:

示例 1:

// Java code to illustrate removeElementAt()
  
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);
  
        // Initial size
        System.out.println("The initial size is: "
                           + stack.size());
  
        // Remove the element at 3rd position
        stack.removeElementAt(2);
  
        // Print the final Stack
        System.out.println("Final Stack: " + stack);
  
        // Final size
        System.out.println("The final size is: "
                           + stack.size());
    }
}
输出:
Stack: [Geeks, for, Geeks, 10, 20]
The initial size is: 5
Final Stack: [Geeks, for, 10, 20]
The final size is: 4

示例 2:

// Java code to illustrate removeElement() 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);
  
        // Initial size
        System.out.println("The initial size is: "
                           + stack.size());
  
        // Remove the element at 1st position
        stack.removeElementAt(0);
  
        // Print the final Stack
        System.out.println("Final Stack: " + stack);
  
        // Final size
        System.out.println("The final size is: "
                           + stack.size());
    }
}
输出:
Stack: [10, 20, 30, 40, 50]
The initial size is: 5
Final Stack: [20, 30, 40, 50]
The final size is: 4