Java Stack removeRange()方法及示例
Java中 Stack 的 removeRange() 方法用于从一个Stack对象中移除指定范围内的所有元素。它将任何后续的元素移到左边。这个调用将堆栈缩短了(toIndex-fromIndex)个元素,其中toIndex是结束索引,fromIndex是开始索引,所有元素都将被移除。(如果toIndex==fromIndex,这个操作没有效果)
语法:
removeRange(int fromIndex, int toIndex)
参数: 该方法需要两个参数:
- fromIndex: 要删除的索引元素的起始索引。
- toIndex: 在[fromIndex-toIndex]范围内,所有元素都被移除。
返回值: 这个方法不返回任何值。它只删除指定范围内的所有元素。
异常: 如果fromIndex或toIndex超出范围(fromIndex = size() or toIndex > size() or toIndex < fromIndex),该方法会抛出indexOutOfBoundsException
下面的例子说明了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
极客教程