Java Stack setSize()方法及示例
Java.util.Stack 类的 setSize() 方法将这个Stack实例的大小改变为作为参数传递的大小。
语法
public void setSize(int size)
Java
参数: 该方法将 新的尺寸 作为一个参数。
异常。如果新的大小是负数,该方法会抛出ArrayIndexOutOfBoundsException。
下面是说明 setSize() 方法的例子。
例1 :
// Java program to demonstrate
// setSize() method for Integer value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
{
try {
// Creating object of Stack<Integer>
Stack<Integer>
stack = new Stack<Integer>();
// adding element to stack
stack.add(10);
stack.add(20);
stack.add(30);
stack.add(40);
// Print the Stack
System.out.println("Stack: " + stack);
// Print the current size of Stack
System.out.println("Current size of Stack: "
+ stack.size());
// Change the size to 10
stack.setSize(10);
// Print the current size of Stack
System.out.println("New size of Stack: "
+ stack.size());
}
catch (Exception e) {
System.out.println("Exception thrown : " + e);
}
}
}
Java
输出:
Stack: [10, 20, 30, 40]
Current size of Stack: 4
New size of Stack: 10
Java
例2 :
// Java program to demonstrate
// setSize() method for String value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
{
try {
// Creating object of Stack<Integer>
Stack<String>
stack = new Stack<String>();
// adding element to stack
stack.add("A");
stack.add("B");
stack.add("C");
stack.add("D");
// Print the Stack
System.out.println("Stack: "
+ stack);
// Print the current size of Stack
System.out.println("Current size of Stack: "
+ stack.size());
// Change the size to -1
stack.setSize(-1);
// Print the current size of Stack
System.out.println("New size of Stack: "
+ stack.size());
}
catch (Exception e) {
System.out.println("Exception thrown : " + e);
}
}
}
Java
输出:
Stack: [A, B, C, D]
Current size of Stack: 4
Exception thrown : java.lang.ArrayIndexOutOfBoundsException: -1
Java