Java.util.Stack类的setSize()方法将此Stack实例的大小更改为作为参数传递的大小。
用法:
public void setSize(int size)
参数:此方法将新大小作为参数。
异常:如果新大小为负,则此方法将引发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);
}
}
}
输出:
Stack: [10, 20, 30, 40] Current size of Stack: 4 New size of Stack: 10
示例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);
}
}
}
输出:
Stack: [A, B, C, D] Current size of Stack: 4 Exception thrown : java.lang.ArrayIndexOutOfBoundsException: -1
相关用法
- Java Vector setSize()用法及代码示例
- Java Stack set()用法及代码示例
- Java Stack pop()用法及代码示例
- Java Stack contains()用法及代码示例
- Java Stack get()用法及代码示例
- Java Stack clone()用法及代码示例
- Java Stack iterator()用法及代码示例
- Java Stack elementAt()用法及代码示例
- Java Stack ensureCapacity()用法及代码示例
- Java Stack firstElement()用法及代码示例
- Java Stack toString()用法及代码示例
- Java Stack hashCode()用法及代码示例
- Java Stack isEmpty()用法及代码示例
- Java Stack clear()用法及代码示例
- Java Stack capacity()用法及代码示例
注:本文由纯净天空筛选整理自Code_r大神的英文原创作品 Stack setSize() method in Java with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。