What Does the Method ensureCapacity(int minCapacity) Do in Java



The ensureCapacity(int minCapacity) method of the class java.util.ArrayList 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.

Example

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String args[]) {
      ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
      arrlist.add(10);
      arrlist.add(50);
      arrlist.add(30);
      arrlist.ensureCapacity(15);
      for (Integer number : arrlist) {
         System.out.println("Number = " + number);
      }
   }
}

Output

Number = 10
Number = 50
Number = 30
Updated on: 2020-02-25T10:10:30+05:30

141 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements