Java ArrayList ensureCapacity() Method Example

The java.util.ArrayList.ensureCapacity(int minCapacity) method increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.

Java ArrayList ensureCapacity() Method Example

The following example shows the usage of java.util.Arraylist.ensureCapacity() method:

import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // create an empty array list with an initial capacity ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // use add method to add elements arrlist.add(10); arrlist.add(50); arrlist.add(30); // this will increase the capacity of the ArrayList to 15 elements arrlist.ensureCapacity(15); // let us print all the elements available in list for (Integer number : arrlist) { System.out.println("Number = " + number); } } }
Let us compile and run the above program, this will produce the following result −
Number = 10 Number = 50 Number = 30

Reference

Java ArrayList Source Code Examples


Comments