Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

ensureCapacity()

Example

Expand the capacity of a list to accommodate 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 boosts the list’s capacity to a specified level, preemptively expanding it if required.

Although it doesn’t visibly alter the list, it enhances code efficiency.

When methods like add() and addAll() are invoked, insufficient capacity prompts additional space allocation, incurring additional processing time. Hence, ensuring adequate capacity beforehand optimizes performance by minimizing such overhead during add() calls.

If you have an estimate of the number of items you’ll add, using ensureCapacity() enables you to expand the list’s capacity in a single operation, optimizing performance for multiple add() calls.

Syntax

public void add(int capacity)

Parameter Values

Parameter

Description

capacity

Mandatory. Indicates the desired capacity of the list, defining the number of items it should be capable of holding.