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 Description:
- minCapacity - The capacity of the dynamic array
Return Value
This method does not return any value.
Example
Example of using the ensureCapacity() method 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 the arraylist
sites.ensureCapacity(3);
sites.add("Google");
sites.add("tutorialpro");
sites.add("Taobao");
System.out.println("Website List: " + sites);
}
}
Executing the above program outputs:
Website List: [Google, tutorialpro, Taobao]
In the example above, we created an array named sites.
Notice this line:
sites.ensureCapacity(3);
We used the ensureCapacity() method to adjust the dynamic array size to accommodate 3 elements.
In Java, ArrayList 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 the 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);
}
}
Executing the above program outputs:
Website List: [Google, tutorialpro, Taobao, Wiki]
In the example above, we used the ensureCapacity() method to adjust the dynamic array size to accommodate 3 elements. However, when we add a fourth element to the arraylist, the arraylist automatically resizes 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.