Can I use ArrayList.trimToSize() method in dynamic arrayList ?
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.