ArrayList
internally implements growable dynamic array which means it can increase and decrease its size automatically. If we try to add an element to a already full ArrayList then it automatically re-sized internally to accommodate the new element however sometimes its not a good approach.
Consider a scenario when there is a need to add huge number of elements to an already full ArrayList, in such case ArrayList has to be resized several number of times which would result in a poor performance. For such scenarios ensureCapacity()
method of Java.util.ArrayList
class is very useful as it increases the size of the ArrayList by a specified capacity.
public void ensureCapacity(int minCapacity)
Example
package beginnersbook.com; import java.util.ArrayList; public class EnsureCapacityExample { public static void main(String args[]) { // ArrayList with Capacity 4 ArrayList<String> al = new ArrayList<String>(4); //Added 4 elements al.add("Hi"); al.add("Hello"); al.add("Bye"); al.add("GM"); //Increase capacity to 5 al.ensureCapacity(5); al.add("GE"); // let us print all the elements available in list for (String temp: al) { System.out.println(temp); } } }
Output:
Hi Hello Bye GM GE
Ray says
Thank you for those easy understanding examples. Is there a typo in al.ensureCapacity(55), (where 55 should be 5 according to the comment)?
Abir Nandy says
It’s not working in my code where I am checking the size of the arraylist after ensuring the capacity.
The code is as follows:-
import java.io.*;
import java.util.*;
class Exp
{
public static void main(String args[])
{
int n,i;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
ArrayList in=new ArrayList();
in.ensureCapacity(n);
System.out.println(in.size());
}
}
Abir Nandy says
When an arraylist is having an element repeated than what will get returned if indexOf() that element has been used?
Chaitanya Singh says
It will return the index of the first occurrence of the element in the list