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


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


Java中的Stack的removeRange()方法用於從Stack對象中刪除指定範圍內的所有元素。它將所有後續元素向左移動。此調用通過(toIndex-fromIndex)元素來縮短堆棧,其中toIndex是結束索引,fromIndex是將刪除所有元素的開始索引。 (如果toIndex == fromIndex,則此操作無效)

用法:

removeRange(int fromIndex, int toIndex)

參數:該方法有兩個參數:


  • fromIndex:從中刪除索引元素的起始索引。
  • toIndex:範圍[fromIndex-toIndex)之內,所有元素均被刪除。

返回值:此方法不返回任何值。它僅刪除指定範圍內的所有元素。

異常:如果fromIndex或toIndex超出範圍,則此方法將引發indexOutOfBoundsException(fromIndex = size()或toIndex> size()或toIndex

以下示例說明了Stack.removeRange()方法:

例子1:演示使用removeRange()方法

// Java program to demonstrate the 
// working of removeRange() method 
  
import java.util.*; 
  
// extending the class to stackyastack since removeRange() 
// is a protected method 
public class GFG extends Stack<Integer> { 
  
    public static void main(String[] args) 
    { 
  
        // create an empty  stack 
  
        GFG stack = new GFG(); 
  
        // use add() method to add values in the stack 
        stack.add(1); 
        stack.add(2); 
        stack.add(3); 
        stack.add(12); 
        stack.add(9); 
        stack.add(13); 
  
        // prints the stack before removing 
        System.out.println("The stack before using removeRange:"
                           + stack); 
  
        // removing range of 1st 2 elements 
        stack.removeRange(0, 2); 
        System.out.println("The stack after using removeRange:"
                           + stack); 
    } 
}
輸出:
The stack before using removeRange:[1, 2, 3, 12, 9, 13]
The stack after using removeRange:[3, 12, 9, 13]

例子2:演示錯誤的程序

// Java program to demonstrate the error in 
// working of removeRange() method 
  
import java.util.*; 
  
// extending the class to stackyastack since removeRange() 
// is a protected method 
public class GFG extends Stack<Integer> { 
  
    public static void main(String[] args) 
    { 
  
        // create an empty stack stack 
  
        GFG stack = new GFG(); 
  
        // use add() method to add values in the stack 
        stack.add(1); 
        stack.add(2); 
        stack.add(3); 
  
        try { 
            // error as 4 is out of range 
            stack.removeRange(1, 4); 
  
            System.out.println("The stack after using removeRange:"
                               + stack); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}
輸出:
java.lang.ArrayIndexOutOfBoundsException


相關用法


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