Java中的 Stack subList() 方法与示例
Java.util.Stack类的subList()方法用于返回此 Stack 在指定 fromIndex(包括)和 toIndex(不包括)之间部分的视图。 (如果 fromIndex 和 toIndex 相等,则返回的 Stack 为空。)
返回的 Stack 由此 Stack 支持,因此返回的 Stack 中的非结构性更改会反映在此 Stack 中,反之亦然。返回的 Stack 支持所有可选的 Stack 操作。
句法:
public Stack subList(int fromIndex, int toIndex)
参数:此方法将以下参数作为参数。
- fromIndex – subList 的低端点(包括)
- toIndex –子列表的高端(不包括)
返回值:此方法返回此堆栈中指定范围的视图。
异常:此方法引发以下异常。
- IndexOutOfBoundsException –如果端点索引值超出范围(fromIndex 大小)
- IllegalArgumentException –如果端点索引乱序(fromIndex > toIndex)
下面是说明subList()方法的示例。
示例 1:
// Java program to demonstrate
// subList() method
// for String value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// Creating object of Stack
Stack
stack = new Stack();
// Populating stack1
stack.add("A");
stack.add("B");
stack.add("C");
stack.add("D");
stack.add("E");
// print stack
System.out.println("Original stack: "
+ stack);
// getting the subList
// using subList() method
List stack2 = stack.subList(2, 4);
// print the subList
System.out.println("SubStack of stack: "
+ stack2);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
Original stack: [A, B, C, D, E]
SubStack of stack: [C, D]
示例 2:对于IndexOutOfBoundsException
// Java program to demonstrate
// subList() method
// for IndexOutOfBoundsException
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// Creating object of Stack
Stack
stack = new Stack();
// Populating stack1
stack.add("A");
stack.add("B");
stack.add("C");
stack.add("D");
stack.add("E");
// print stack
System.out.println("Original stack: "
+ stack);
// getting the subList
// using subList() method
System.out.println("\nEnd index value is out of range");
List stack2 = stack.subList(2, 7);
// print the subList
System.out.println("SubStack of stack: "
+ stack2);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
Original stack: [A, B, C, D, E]
End index value is out of range
java.lang.IndexOutOfBoundsException: toIndex = 7
示例 3:对于IllegalArgumentException
// Java program to demonstrate
// subList() method
// for IllegalArgumentException
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
// Creating object of Stack
Stack
stack = new Stack();
// Populating stack1
stack.add("A");
stack.add("B");
stack.add("C");
stack.add("D");
stack.add("E");
// print stack
System.out.println("Original stack: "
+ stack);
// getting the subList
// using subList() method
System.out.println("\nEndpoint indices "
+ "are out of order"
+ " (fromIndex > toIndex)");
List stack2 = stack.subList(7, 2);
// print the subList
System.out.println("SubStack of stack: "
+ stack2);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
Original stack: [A, B, C, D, E]
Endpoint indices are out of order (fromIndex > toIndex)
java.lang.IllegalArgumentException: fromIndex(7) > toIndex(2)