Home »
Java programming language
Java ArrayList ensureCapacity() Method with Example
ArrayList Class ensureCapacity() method: Here, we are going to learn about the ensureCapacity() method of ArrayList Class with its syntax and example.
Submitted by Preeti Jain, on January 18, 2020
ArrayList Class ensureCapacity() method
- ensureCapacity() method is available in java.util package.
- ensureCapacity() method is used to ensure the capacity of this Arraylist (i.e. It can save minimum the number of elements given by the parameter).
- ensureCapacity() method is a non-static method so it is accessible with the class object and if we try to access the method with the class name then we will get an error.
- ensureCapacity() method does not throw an exception at the time of ensuring capacity.
Syntax:
public void ensureCapacity(int minCap);
Parameter(s):
- int minCap – represents the targeted minimum capacity.
Return value:
The return type of the method is void, it returns nothing.
Example:
// Java program to demonstrate the example
// of void ensureCapacity(int) method of ArrayList.
import java.util.*;
public class EnsureCapacityOfArrayList {
public static void main(String[] args) {
// Create an ArrayList with initial
// capacity of storing elements
ArrayList < String > arr_l = new ArrayList < String > (10);
// By using add() method is to add
// elements in this ArrayList
arr_l.add("C");
arr_l.add("C++");
arr_l.add("JAVA");
arr_l.add("DOTNET");
arr_l.add("PHP");
// By using ensureCapacity(int) method is to
// ensure the capacity to store 30 elements
// of this ArrayList
arr_l.ensureCapacity(30);
// Display ArrayList
System.out.println("arr_l.ensureCapacity(30) : " + arr_l);
}
}
Output
arr_l.ensureCapacity(30) : [C, C++, JAVA, DOTNET, PHP]