Can I use ArrayList.trimToSize() method in dynamic arrayList ?
Thanks in advance.
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.
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.
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.
See above. I don't think it's very likely you'll ever use this.
trimToSize()
from the source:
public void trimToSize() {
modCount++;
int oldCapacity = elementData.length;
if (size < oldCapacity) {
elementData = Arrays.copyOf(elementData, size);
}
}
Well, that's simple:
But seriously: There are few occasions where this method should be called (I personally have never used it). It's related to how an ArrayList is implemented: As the name suggests, the ArrayList internally uses an array to store the data. When you add new elements to the ArrayList, the size of the array is increased as needed. When you add 1000000 elements to the ArrayList, then the internal Array will have a .length of at least (!) 1000000. When you afterwards remove 999999 elements from the ArrayList, then the internal array will still have a .length of at least 1000000. The call to trimToSize
will then make sure that the internal array only has the required size (1, in this case). But again: This is hardly ever necessary or beneficial. You should usually not work on ArrayList
instances anyhow, but on the (more general) List
interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With