English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java ArrayList sureCapacity() method sets the size of ArrayList using the specified capacity.
Syntax of ensureCapacity() method
arraylist.ensureCapacity(int minCapacity)
minCapacity - The specified minimum capacity of ArrayList
The ensureCapacity() method does not return any value.
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
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.