Java ArrayList ensureCapacity() Method
Example
Increase the capacity of a list to 15 items:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.ensureCapacity(15);
for (int i = 1; i <= 15; i++) {
list.add(i);
}
System.out.println(list);
}
}
Definition and Usage
The ensureCapacity()
method increases the capacity of a list to a specified amount, if necessary.
This method does not have a visible effect but it can make code more efficient.
When methods such as add()
and addAll()
are called, if the capacity of a list is not large enough then some extra work is done to add enough space for the new items. It takes a bit of time to do this, so having this happen with every add()
call is not ideal.
If you know approximately how many items you are going to add, the ensureCapacity()
method allows you to increase the capacity of the list just once for multiple add()
calls.
Syntax
public void add(int capacity)
Parameter Values
Parameter | Description |
---|---|
capacity | Required. Specifies the number of items that the list should be able to hold. |
Related Pages
❮ ArrayList Methods