Java ArrayList.ensureCapacity() Method
public void ensureCapacity(int minCapacity)
The ensureCapacity() method is used to increase the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements which is not smaller than the specified size.
Package: java.util
Java Platform: Java SE 8
Syntax:
ensureCapacity(int minCapacity)
Parameters:
Name | Description | Type |
---|---|---|
minCapacity | The minimum length for an ArrayList instance. | int |
Return Value:
This method does not return any value.
Pictorial presentation of ArrayList.ensureCapacity() Method
Example: ArrayList.ensureCapacity Method
import java.util.*;
public class test {
public static void main(String[] args) {
// ArrayList with Capacity 4
ArrayList<String> StudentList = new ArrayList<String>(4);
//Added 4 elements
StudentList.add("David");
StudentList.add("Tom");
StudentList.add("Rohit");
StudentList.add("Paul");
//Increase capacity to 10
StudentList.ensureCapacity(10);
StudentList.add("Vishal");
// Print all the elements available in list
for (String s: StudentList) {
System.out.println(s);
}
}
}
Output:
F:\java>javac test.java F:\java>java test David Tom Rohit Paul Vishal
Java Code Editor:
Previous:JtrimToSize Method
Next:size Method
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-tutorial/arraylist/arraylist_ensurecapacity.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics