要检查Java的容量,首先创建一个列表并添加元素。之后使用ensureCapacity()
并增加容量。
让我们首先创建一个ArrayList并添加一些元素-
ArrayList<Integer>arrList = new ArrayList<Integer>(5); arrList.add(100); arrList.add(200); arrList.add(300); arrList.add(400); arrList.add(500);
现在,增加ArrayList的容量-
arrList.ensureCapacity(15);
同时,使用该size()
方法,您还可以检查ArrayList的当前大小。
import java.util.ArrayList; public class Demo { public static void main(String[] a) { ArrayList<Integer>arrList = new ArrayList<Integer>(5); arrList.add(100); arrList.add(200); arrList.add(300); arrList.add(400); arrList.add(500); arrList.add(600); arrList.add(700); System.out.println("Size of list = "+arrList.size()); arrList.ensureCapacity(15); for (Integer number: arrList) { System.out.println(number); } arrList.add(100); arrList.add(200); arrList.add(300); arrList.add(400); arrList.add(500); System.out.println("Updated list..."); System.out.println("Size of list = "+arrList.size()); arrList.ensureCapacity(15); for (Integer number: arrList) { System.out.println(number); } } }
输出结果
Size of list = 7 100 200 300 400 500 600 700 Updated list... Size of list = 12 100 200 300 400 500 600 700 100 200 300 400 500