Java中的堆栈removeRange()方法与示例
Java中Stack的removeRange()方法用于从 Stack 对象中移除指定范围内的所有元素。它将任何后续元素向左移动。此调用通过 (toIndex-fromIndex) 元素缩短堆栈,其中 toIndex 是结束索引,fromIndex 是要删除所有元素的起始索引。 (如果toIndex==fromIndex,这个操作没有效果)
句法:
removeRange(int fromIndex, int toIndex)
参数:此方法有两个参数:
- fromIndex:要从中删除索引元素的起始索引。
- toIndex:在 range[fromIndex-toIndex) 内,所有元素都被删除。
返回值:此方法不返回任何值。它只删除指定范围内的所有元素。
异常:如果 fromIndex 或 toIndex 超出范围(fromIndex = size() 或 toIndex > size() 或 toIndex < fromIndex),此方法将抛出indexOutOfBoundsException
下面的示例说明了 Stack.removeRange() 方法:
示例 1 :演示 removeRange() 方法的使用
Java
// 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 {
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);
}
}
Java
// 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 {
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);
}
}
}
输出:
The stack before using removeRange:[1, 2, 3, 12, 9, 13]
The stack after using removeRange:[3, 12, 9, 13]
示例 2 :演示错误的程序
Java
// 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 {
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