ArrayList: The ensureCapacity() method in Java
ArrayList implements a dynamic, growing array structure, which means that the size changes automatically. If you try to add an element to an already populated ArrayList then, it will be automatically resized.We consider a scenario where we need to add a very large number of elements to an ArrayList of insufficient size, in such a case, the ArrayList has to be resized several times and this will lead to poor performance. This problem can be addressed by calling the ensureCapacity() which is very useful for ensuring or increasing the capacity of an ArrayList.
public void ensureCapacity(int minCapacity): This method resets the minimum capacity of ArrayList.
import java.util.ArrayList;Runtime:
public class ArrayList_ensureCapacity {
public static void main(String[] args) {
ArrayList< String> arraylist = new ArrayList< String> (4);
//Add Items to ArrayList
arraylist.add("Screen");
arraylist.add("TV");
arraylist.add("Laptop");
arraylist.add("Tablet");
arraylist.ensureCapacity(5);
arraylist.add("Smartphone");
System.out.println("ArrayList Elements: ");
for(String s:arraylist)
System.out.println(s);
}
}
ArrayList items:
Screen
TV
Laptop
Tablet
Smartphone