English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (FIFO)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Other Java Topics

Usage and Example of Java ArrayList ensureCapacity()

Java ArrayList Methods

The Java ArrayList sureCapacity() method sets the size of ArrayList using the specified capacity.

Syntax of ensureCapacity() method

arraylist.ensureCapacity(int minCapacity)

Parameters of sureCapacity()

  • minCapacity - The specified minimum capacity of ArrayList

Return value of sureCapacity()

The ensureCapacity() method does not return any value.

Example1Java ArrayList sureCapacity()

import java.util.ArrayList;
class Main {
  public static void main(String[] args) {
    ArrayList<String> languages = new ArrayList<>();
    //Set the capacity of the arraylist
    languages.ensureCapacity(3);
    //Add elements to ArrayList
    languages.add("Java");
    languages.add("Python");
    languages.add("C");
    System.out.println("ArrayList: ", + languages);
  }
}

Output Result

ArrayList: [Java, Python, C]

In the above example, we created an arraylist named languages. Note this line,

languages.ensureCapacity(3);

Here, the ensureCapacity() method adjusts the size of arraylist to store3elements.

However, ArrayList in Java is dynamic and can adjust its size. That is, if we add3more than one element, it will automatically adjust its size. For example

Example2Usage of ensureCapacity()

import java.util.ArrayList;
class Main {
  public static void main(String[] args) {
    ArrayList<String> languages = new ArrayList<>();
    //Set the capacity of the arraylist
    languages.ensureCapacity(3);
    //Add elements to ArrayList
    languages.add("Java");
    languages.add("Python");
    languages.add("C");
    //add the4elements
    languages.add("Swift");
    System.out.println("ArrayList: ", + languages);
  }
}

Output Result

ArrayList: [Java, Python, C, Swift]

In the above example, we use ensureCapacity() method to adjust the size of arraylist to store3elements. However, when we add the4elements, arraylist will automatically adjust its size.

thenIf arraylist can automatically adjust its size,Why use guaranteeCapacity() method to adjust the size of arraylist?

This is because if we use ensureCapacity() to adjust the size of ArrayList, it will be adjusted to the specified capacity immediately.Otherwise, the size of arraylist will be adjusted each time an element is added.

Java ArrayList Methods