Java.util.ArrayList.ensureCapacity() Method

Advertisements


Description

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

Declaration

Following is the declaration for java.util.ArrayList.ensureCapacity() method

public void ensureCapacity(int minCapacity)

Parameters

  • minCapacity -- This is the desired minimum capacity.

Return Value

This method does not return any value.

Exception

  • NA

Example

The following example shows the usage of java.util.Arraylist.ensureCapacity() method.

package com.tutorialspoint;

import java.util.ArrayList;

public class ArrayListDemo {
  public static void main(String args[]) {

    // create an empty array list with an initial capacity
    ArrayList<Integer> arrlist = new ArrayList<Integer>(5);

    // use add method to add elements
    arrlist.add(10);
    arrlist.add(50);
    arrlist.add(30);
	
    // this will increase the capacity of the ArrayList to 15 elements
    arrlist.ensureCapacity(15);

    // let us print all the elements available in list
    for (Integer number : arrlist) {
      System.out.println("Number = " + number);
    }
  }
}

Let us compile and run the above program, this will produce the following result:

Number = 10
Number = 50
Number = 30



Advertisements
Advertisements