Flash cards
Review the key moves
What is the main idea behind Java ArrayList ensureCapacity() Method?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___ java.util.ArrayList;Put the learning moves in the order that makes the concept easiest to apply.
❮ ArrayList Methods
Example
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. |