当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。