Java ArrayList check capacity

Introduction

The List capacity tracks the number of elements the list can hold before enlarging it.

We can use the ensureCapacity() method to check that the internal data structure has enough capacity before adding elements.

import java.util.ArrayList;

public class Main {
  public static void main(String[] a) {

    ArrayList<String> list = new ArrayList<>();
    System.out.println(list.size());
    /*w  w  w.  ja v  a2s . c  o m*/
    list.ensureCapacity(200);
    for(int i=0;i<100;i++) {
      list.add("A");  
    }
    
    System.out.println(list);

    
  }
}



PreviousNext

Related