What are the consequences if we store huge objects collection in Arraylist when it is not expecting them (i.e we may initialized the Arraylist to accommodate 10/100/1000 objects, however at runtime we might store some 100 thousand objects).
and which is better out of below two in case we know this will happen at some point of time. 1).To create a empty arraylist or 2).Create a arraylist with predefined case. or both doesn't matter they are same?
4 Answers 4
You will be able to insert enough objects up to the initial size of the ArrayList
without it being resized. The next object you add to the ArrayList will cause it to resize (see ensureCapacity
), doubling the capacity of the ArayList.
See Also
2 Comments
add(E)
method it will increase the size of the array and add the element to the end. If however you use attempt to add an element at a specific index i.e. add(int, E)
and you provide an index past the end of the array, it will fail.Not much. It doubles the size of the backing array every time it runs out. There is a worst case that it will be almost double the size of the contents, and when creating that co-exist with an array half that size. Unless they are flyweights, the objects referenced should take considerably more memory.
Comments
The capacity of the ArrayList will be increased by ensureCapacity.
Comments
For this, you'll have to do a benchmark test.
As for ArrayList, arraylist was designed to always resize to handle as many objects as possible (as long as the JVM can keep all these objects in a stack).
You don't ever need to worry about making the array full though.