Monday, 25 April 2016

What is the use of trimToSize() method of ArrayList ?


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

If 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.

Example
ArrayList<Integer> arraylist = new ArrayList<Integer>(10);
arraylist.add(1);
arraylist.add(2);
arraylist.add(3);

// Debug the capacity of array list = 10
// [1, 2, 3, null, null, null, null, null, null, null]
System.out.println(arraylist.size());

arraylist.trimToSize();

// Debug the capacity of array list = 3
// [1, 2, 3]
System.out.println(arraylist.size());

// size() prints the actual number of elements, but not capacity

Output
3
3

No comments:

Post a Comment

Note: only a member of this blog may post a comment.