user1613360 user1613360 - 1 year ago 134
Java Question

Is Java Array list trimToSize() method redundant?

I think

method in Java's ArrayList is unnecessary. My understanding is:

Let's take an array of integers:

int[] a = new int[10]; //This allocates ten free slots proactively.

The major advantage of ArrayList is it can create arrays dynamically at run time thus saving memory. Now the code
ArrayList<Integer> arl = new ArrayList<Integer>(10);
will not assign ten free slots proactively; instead it adds slots only when there is data to be stored.

Now Java specification says
will remove the unused space from ArrayList, but according to my understanding there won't be any unused space in ArrayList because space is created only when data is available, and when data is available the unused or free space will be nil.

Answer Source

Your understanding is incorrect. If you create a new ArrayList<Integer>(10), it will create an array of Integer of size 10 filled with nulls inside of the ArrayList as the nucleus of its data model. It will fill some or all of the slots depending on the number of items, and it will increase the size of the underlying array if the number of items exceeds its number of possible size. The trimToSize() method has relevance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download