Java ArrayList ensureCapacity() Method
The ensureCapacity() method is used to set the capacity of the dynamic array to a specified size.
The syntax for the ensureCapacity() method is:
arraylist.ensureCapacity(int minCapacity)
Note: arraylist is an object of the ArrayList class.
Parameter:
- minCapacity - the capacity of the dynamic array
Return Value
This method does not return any value.
Example
Example of using ensureCapacity() with ArrayList:
Example
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// Create a dynamic array
ArrayList<String> sites = new ArrayList<>();
// Set the capacity of arraylist
sites.ensureCapacity(3);
sites.add("Google");
sites.add("tutorialpro");
sites.add("Taobao");
System.out.println("Website List: " + sites);
}
}
Output of the above program is:
Website List: [Google, tutorialpro, Taobao]
In the above example, we created an array named sites.
Notice this line:
sites.ensureCapacity(3);
We used the ensureCapacity() method to adjust the dynamic array size to hold 3 elements.
ArrayList in Java can dynamically resize itself. This means if we add more than 3 elements to the arraylist, it will automatically adjust its size, for example:
Example
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// Create a dynamic array
ArrayList<String> sites = new ArrayList<>();
// Set the capacity of arraylist
sites.ensureCapacity(3);
sites.add("Google");
sites.add("tutorialpro");
sites.add("Taobao");
// Add a fourth element
sites.add("Wiki");
System.out.println("Website List: " + sites);
}
}
Output of the above program is:
Website List: [Google, tutorialpro, Taobao, Wiki]
In the above example, we used the ensureCapacity() method to adjust the dynamic array size to hold 3 elements. However, when we add a fourth element to the arraylist, the arraylist will automatically resize itself.
So, if the arraylist can automatically resize itself, why use the ensureCapacity() method to adjust the size of the arraylist?
This is because if we use the ensureCapacity() method to adjust the size of the arraylist, it will immediately resize to the specified capacity. Otherwise, the arraylist would resize each time an element is added.