ArrayList ensureCapacity(int minCapacity) method in java

Let’s learn ArrayList ensureCapacity(int minCapacity) method in java.

ArrayList ensureCapacity(int minCapacity) method in java

ensureCapacity(int minCapacity) method of ArrayList class increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.

Syntax:

public void ensureCapacity(int minCapacity)

Parameters:

minCapacity the desired minimum capacity.

Returns:

this method does not return any value.

Now let’s see example on ArrayList ensureCapacity(int minCapacity) method.

import java.util.ArrayList;
public class ArrayListEnsureCapacityMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<Integer> al = new ArrayList<Integer>(5);
      al.add(25);
      al.add(36);
      al.add(50);
      // increase the capacity of ArrayList to 10 elements
      al.ensureCapacity(10);
      // printing all the elements available in list
      for(Integer num : al)
      {
         System.out.println("Numbers: " + num);
      }
   }
}

Output:

Numbers: 25
Numbers: 36
Numbers: 50


Also read – operators in java