bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Reference
Java•Java Reference

Java ArrayList ensureCapacity() Method

Flash cards

Review the key moves

1/4
Core idea

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.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ java.util.ArrayList;
3Order

Put the learning moves in the order that makes the concept easiest to apply.

The ensureCapacity() method increases the capacity of a list to a specified amount, if necessary.
Definition and Usage
Java ArrayList ensureCapacity() Method

❮ 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

ParameterDescription
capacityRequired. Specifies the number of items that the list should be able to hold.

Previous

Java ArrayList contains() Method

Next

Java ArrayList forEach() Method