Java ArrayList - ensureCapacity() Method
The java.util.ArrayList.ensureCapacity() method is used to increase the capacity of the given ArrayList, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.
Syntax
public void ensureCapacity(int minCapacity)
Parameters
minCapacity |
Specify the desired minimum capacity. |
Return Value
void type.
Exception
NA.
Example:
In the example below, the java.util.ArrayList.ensureCapacity() method is used to increase the capacity of the list.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating an ArrayList ArrayList<Integer> MyList = new ArrayList<Integer>(5); //populating the ArrayList MyList.add(10); MyList.add(20); MyList.add(30); MyList.add(40); MyList.add(50); //print the content of the ArrayList System.out.println("MyList contains: " + MyList); //increase the capacity of the ArrayList to 10 MyList.ensureCapacity(10); //Add more elements to the ArrayList MyList.add(60); MyList.add(70); //print the content of the ArrayList System.out.println("MyList contains: " + MyList); } }
The output of the above code will be:
MyList contains: [10, 20, 30, 40, 50] MyList contains: [10, 20, 30, 40, 50, 60, 70]
❮ Java.util - ArrayList