Cataclysm Cataclysm - 1 year ago 97
Java Question

ArrayList.trimToSize() method

Can I use ArrayList.trimToSize() method in dynamic arrayList ?

  1. If I use it , what will be happened ?

  2. Can I get any benefits on using this method on dynamic ArrayList.

  3. In which case, I should use this method.

Thanks in advance.

Answer Source

From the docs you link yourself:

Trims the capacity of this ArrayList instance to be the list's current size. An application can use this operation to minimize the storage of an ArrayList instance.

Internally an ArrayList stores an array that holds all the items. At certain moments the ArrayList will "expand" this array by copying all values into a larger array. This happens whenever an item is being added and the required capacity is bigger than the current one. What happens at this point is the following line of code:

int newCapacity = oldCapacity + (oldCapacity >> 1);
elementData = Arrays.copyOf(elementData, newCapacity);

In essence this will create a new array that is 1.5 times the size of the current one. What this method does is resize the internal array so that it has no empty space left.

  1. Nothing will happen that's visible to you. You won't lose any data, it's just smaller backing array. Adding data to the arraylist will again expand the array normally.

  2. I assume you mean a "normal" ArrayList. If you use this, you will reduce the memory used but it will also be futile if you will still add data after that AND it is pretty useless for small lists. If you have an ArrayList of many, many items and you're sure you don't want to add anymore then you can call this method to reduce some memory footprint.

  3. See above. I don't think it's very likely you'll ever use this.

trimToSize() from the source:

public void trimToSize() {
    int oldCapacity = elementData.length;
    if (size < oldCapacity) {
        elementData = Arrays.copyOf(elementData, size);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download