What is the best way to check capacity in Java?


To check capacity in Java, firstly create a list and add elements. After that use ensureCapacity() and increase the capacity.

Let us first create an ArrayList and add some elements −

ArrayList<Integer>arrList = new ArrayList<Integer>(5);
arrList.add(100);
arrList.add(200);
arrList.add(300);
arrList.add(400);
arrList.add(500);

Now, increase the capacity of the ArrayList −

arrList.ensureCapacity(15);

Meanwhile, with the size() method, you can check the current size of the ArrayList as well.

Example

 Live Demo

import java.util.ArrayList;
public class Demo {
   public static void main(String[] a) {
      ArrayList<Integer>arrList = new ArrayList<Integer>(5);
      arrList.add(100);
      arrList.add(200);
      arrList.add(300);
      arrList.add(400);
      arrList.add(500);
      arrList.add(600);
      arrList.add(700);
      System.out.println("Size of list = "+arrList.size());
      arrList.ensureCapacity(15);
      for (Integer number: arrList) {
         System.out.println(number);
      }
      arrList.add(100);
      arrList.add(200);
      arrList.add(300);
      arrList.add(400);
      arrList.add(500);
      System.out.println("Updated list...");
      System.out.println("Size of list = "+arrList.size());
      arrList.ensureCapacity(15);
      for (Integer number: arrList) {
         System.out.println(number);
      }
   }
}

Output

Size of list = 7
100
200
300
400
500
600
700
Updated list...
Size of list = 12
100
200
300
400
500
600
700
100
200
300
400
500

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

859 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements