I' m unable to understand the purpose of the ensureCapacity() method in ArrayList. It does not help in any way.The following is my code.
I had commented the last 2 objects passed in the arrayList which reduces its its size to 4. Later I removed the comments which increases its size to 6. The ensureCpacity as is set to 5 does not give an exception or an error when elements are removed or added. please tell me the use of the ensureCapacity() method.
An ArrayList is a wrapper around an array. Arrays cannot be resized, so if you want to increase the size of the array, you need to create a new array of the required size and then copy all the elements from the old array to the new array.
So, in simple terms, assume you have an ArrayList with 5 elements in it. If you call the add method to add another element, what will actually happen in the background is that a new array of size 6 will be created, all the existing elements from the old array will be copied into the new array and then the new element will be added to the new array. Now, what if you were going to to add a thousand new elements to the ArrayList by calling get() a thousand times ? Each time, a new array would be created and all the elements copied from the old array. This is inefficient.
However, if you know you are going to add a thousand elements to the ArrayList, if you call the ensureCapacity method first, this will create a new array with room for all those new elements. Now, every time you call get, the array will already be large enough to accomodate the new element, so no more array creation and copying will be needed.
Joined: Oct 06, 2008
why do we have to initialize the capacity of an ArrayList or reinitialise it later when collections are primarily used for dynamic assignment.