Java ArrayList trim to size

Introduction

The trimToSize() method makes sure that there is no unused space in the underline data structure for ArrayList.

import java.util.ArrayList;

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

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

    list.trimToSize();
  
  }
}



PreviousNext

Related