What is the best way to check capacity in Java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 24-Apr-2019 12:32:44
Advertisements