When to use EnsureCapacity method in Java

Discussion in 'Generics and Collections' started by muralidhar.9e, Jan 9, 2014.

  1. muralidhar.9e

    muralidhar.9e New Member

    In java Colleciton framework ArrayList and Vector classes contains ensureCapacity(int minCapacity) method to reduce or manage the amount of incremental memory allocation.

    Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

    An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
    Syntax: void ensureCapacity(int minCapacity)
    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.

    For more indetail explanation to understand with programs. Visit Here
     
    Last edited: Jan 9, 2014

  2. 3dtech

    3dtech New Member

    The ensureCapacity() method is used to increase the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements which is not smaller than the specified size.

    Package: java.util

    Java Platform : Java SE 8

    example:

    import java.util.*;

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

    // ArrayList with Capacity 4
    ArrayList<String> StudentList = new ArrayList<String>(4);
    //Added 4 elements
    StudentList.add("David");
    StudentList.add("Tom");
    StudentList.add("Rohit");
    StudentList.add("Paul");

    //Increase capacity to 10
    StudentList.ensureCapacity(10);

    StudentList.add("Vishal");
    // Print all the elements available in list
    for (String s: StudentList) {
    System.out.println(s);
    }
    }
    }


    output:

    F:\java>javac test.java
    F:\java>java test
    David
    Tom
    Rohit
    Paul
    Vishal
     

Share This Page