If you have an ArrayList that already has lots of elements and you are trying to add more elements to the ArrayList, this may degrade the performance of the system. To improve the performance, you may consider using the ensureCapacity() method.
public void ensureCapacity(int minCapacity) , ensures that the ArrayList can atleast hold the number of elements that are specified in int minCapacity.
So when you try to add more elements to the already loaded ArrayList, you can be sure that their is very minimum performance issue.
ArrayList ensureCapacity example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.kscodes.sampleproject; import java.util.ArrayList; public class ArrayListEnsureCapacity { public static void main(String[] args) { // Create an ArrayList ArrayList<String> arrayList1 = new ArrayList<>(); arrayList1.add("Java"); arrayList1.add("JSP"); arrayList1.add("JavaScript"); // Use ensureCapacity to increase the capacity of arraylist arrayList1.ensureCapacity(20); arrayList1.add("Spring"); System.out.println("Printing elements from ArrayList that we added "); for (String element : arrayList1) { System.out.println(element); } } } |
Output
1 2 3 4 5 |
Printing elements from ArrayList that we added Java JSP JavaScript Spring |