當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Stack removeElementAt()用法及代碼示例


Java.util.Stack.removeElementAt(int index)方法用於從特定位置或索引中從Stack中刪除元素。在此過程中,在將移除的元素向下移動一個位置之後,堆棧的大小會自動減小一個,而所有其他元素都會自動減小。

用法:

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<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); 
  
        // 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<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); 
  
        // 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


相關用法


注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 Stack removeElementAt() method in Java with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。