When we create an ArrayList in Java, it is created with a default capacity of 10. However an ArrayList can be automatically resized if more elements are added than the initial capacity of ArrayList. This is useful, as you do not need to worry about the size of ArrayList. However if you are sure about the minimum number of elements that needs to be added to the ArrayList, you can specify that using the ensureCapacity()
method.
Why we need to increase the size of ArrayList?
You may be wondering, why we need to increase the size of ArrayList, if it is already resized whenever needed. The reason is simple, to avoid the performance issues due to continuous resizing of an ArrayList.
For example: you are sure that you need to add at-least 1000 elements to an ArrayList, you can specify that number using ensureCapacity(), however if you do not specify this, the ArrayList needs to be resized multiple number of times. By specifying the capacity in the beginning you ensure the better performance for the add operation on ArrayList.
How to Increase the capacity (Size) of ArrayList?
In the following program, we have created an ArrayList with the initial capacity of 5. We want to store minimum 1000 elements to this ArrayList. For this, we are using ensureCapacity(1000)
. We have placed this method inside try-catch block to handle any exception. If the program throws any exception, print the exception else print a successful message “ArrayList can now store upto 1000 elements”.
import java.util.ArrayList; public class JavaExample { public static void main(String[] arg) throws Exception { try { // Creating an ArrayList with the initial capacity of 5 ArrayList<String> city = new ArrayList<String>(5); // Adding elements to the ArrayList city.add("Pune"); city.add("Noida"); city.add("Agra"); city.add("Delhi"); city.add("Chennai"); // Print the ArrayList System.out.println("ArrayList: " + city); System.out.println("Increasing the capacity to 1000."); // Increasing the capacity of ArrayList to 1000 city.ensureCapacity(1000); //If execution reached at this statement, it means no exception //is thrown and the increase capcity operation is successful. System.out.println("ArrayList can now store upto 1000 elements."); } catch (NullPointerException e) { System.out.println("Cannot increase capacity: " + e); } } }
Output:
ArrayList: [Pune, Noida, Agra, Delhi, Chennai] Increasing the capacity to 1000. ArrayList can now store upto 1000 elements.
Recommended Articles: