Java ArrayList ensureCapacity() Method

ensureCapacity() Method

What is ArrayList in Java ?

Arraylist is a part of collection framework in java. It contains several inbuilt function like ensureCapacity()method which can be found in the java.util.ArrayList Package. It implements the List interface of the collections framework.

Java ArrayList ensureCapacity() Method :

The ensureCapacity() function of the Java.util package. If necessary, the ArrayList class extends this ArrayList instance’s capacity to make sure it can carry at least the amount of elements indicated by the minimum capacity argument.

Syntax  :

public void ensureCapacity(int minCapacity)

clear() Function in ArrayList

clone() Function in ArrayList

add() Function in ArrayList

addall() Function in ArrayList

java ArrayList ensureCapacity()

Example 1 :  

Run

import java.util.*;
public class Main {
    public static void main(String[] args) {

        //ArrayList object creation
        ArrayList<String> list = new ArrayList<>();

        //Adding elements to the list
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");
        list.add("F");

        
        //Printing the initial list.
        System.out.println("ArrayList : " + list);
        
        //Ensuring the minimum size of the list so it can hold at least 12 elements.
        list.ensureCapacity(12);

        //Printing the list after ensureCapacity()
        System.out.println("ArrayList after ensureCapacity() : " + list);
    }
}

Output :

ArrayList : [A, B, C, D, E, F]
ArrayList after trimToSize() : [A, B, C, D, E, F]

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription