📜  Java中的 ArrayList ensureCapacity() 方法及示例

📅  最后修改于: 2022-05-13 01:55:44.720000             🧑  作者: Mango

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
            ArrayList
                arrlist = new ArrayList();
  
            // 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
            ArrayList
                arrlist = new ArrayList();
  
            // 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.