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


Java ArrayList ensureCapacity()用法及代碼示例


如有必要,java.util.ArrayList類的ensureCapacity()方法會增加此ArrayList實例的容量,以確保它至少可以容納最小容量參數指定的元素數量。

用法:

public void ensureCapacity(int minCapacity)

參數:該方法將所需的最小容量作為參數。


以下示例說明了ensureCapacity()方法。

示例1:

// Java program to demonstrate 
// ensureCapacity() method for Integer value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
  
        try { 
  
            // Creating object of ArrayList<Integer> 
            ArrayList<Integer> 
                arrlist = new ArrayList<Integer>(); 
  
            // adding element to arrlist 
            arrlist.add(10); 
            arrlist.add(20); 
            arrlist.add(30); 
            arrlist.add(40); 
  
            // Print the ArrayList 
            System.out.println("ArrayList: "
                               + arrlist); 
  
            // ensure that the ArrayList 
            // can hold upto 5000 elements 
            // using ensureCapacity() method 
            arrlist.ensureCapacity(5000); 
  
            // Print 
            System.out.println("ArrayList can now"
                               + " surely store upto"
                               + " 5000 elements."); 
        } 
  
        catch (NullPointerException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
輸出:
ArrayList: [10, 20, 30, 40]
ArrayList can now surely store upto 5000 elements.

示例2:

// Java program to demonstrate 
// ensureCapacity() method for String value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
  
        try { 
  
            // Creating object of ArrayList<Integer> 
            ArrayList<String> 
                arrlist = new ArrayList<String>(); 
  
            // adding element to arrlist 
            arrlist.add("A"); 
            arrlist.add("B"); 
            arrlist.add("C"); 
            arrlist.add("D"); 
  
            // Print the ArrayList 
            System.out.println("ArrayList: "
                               + arrlist); 
  
            // ensure that the ArrayList 
            // can hold upto 400 elements 
            // using ensureCapacity() method 
            arrlist.ensureCapacity(400); 
  
            // Print 
            System.out.println("ArrayList can now"
                               + " surely store upto"
                               + " 400 elements."); 
        } 
  
        catch (NullPointerException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
輸出:
ArrayList: [A, B, C, D]
ArrayList can now surely store upto 400 elements.


相關用法


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