當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Stack setSize()用法及代碼示例


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


相關用法


注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 Stack setSize() method in Java with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。