![]() |
VOOZH | about |
In Java, the ArrayList.ensureCapacity() method is used to increase the internal capacity of an ArrayList to ensure that it can hold a specified minimum number of elements. It helps to optimize performance by reducing the number of dynamic reallocations when adding a large number of elements.
Example 1: Here, we are using the ensureCapacity() method to preallocate space for an ArrayList of integers before adding elements.
[1, 2, 3, 4, 5]
Explanation: In the above example, we preallocate capacity for an ArrayList of integers before adding 5 elements to optimize memory usage.
public void ensureCapacity(int minCapacity)
Parameter: minCapacity: The minimum desired capacity for the ArrayList.
Example 2: Here, we are using the ensureCapacity() method to preallocate space for a String ArrayList and to add elements.
[Ram, Shyam, Hari]
Explanation: In the above example, we preallocate capacity for an ArrayList of strings and then add a few names to the list.
Example 3: Here, we ensure capacity for an ArrayList when dealing with large data additions.
Size of an ArrayList: 200
Explanation: In the above example, we preallocate the capacity for an ArrayList to handle a large dataset of 200 elements.