Tuesday, 27 October 2015

Java ArrayList trimToSize() Method

Java ArrayList trimToSize() Method

trimToSize() method is used for memory optimization. It trims the capacity of ArrayList to the current list size.

public void trimToSize()

Given arraylist is having capacity of 10 but there are only 3 elements in it, calling trimToSize() method on this ArrayList would change the capacity from 10 to 3.



class TrimToSizeExample {

     public static void main(String args[]) {
           ArrayList<Integer> arraylist = new ArrayList<Integer>(10);
           arraylist.add(1);
           arraylist.add(2);
           arraylist.add(3);
                        // debug and find that the capacity of array list is 10
             // [1, 2, 3, null, null, null, null, null, null, null]
           System.out.println(arraylist.size());

           arraylist.trimToSize();

                        // debug and find that the capacity of array list is 3
             // [1, 2, 3]
           System.out.println(arraylist.size());
     }
}
Output:
3
3

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...