views:

43

answers:

4

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 doesnt matter they are same???

+1  A: 

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.

Tom Hawtin - tackline
A: 

The capacity of the ArrayList will be increased by ensureCapacity.

InsertNickHere
A: 

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

krock
so is it done automatically or we have to make sure it happens??
AutoMEta
if you use the [`add(E)`](http://download-llnw.oracle.com/javase/6/docs/api/java/util/ArrayList.html#add%28E%29) 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)`](http://download-llnw.oracle.com/javase/6/docs/api/java/util/ArrayList.html#add%28int,%20E%29) and you provide an index past the end of the array, it will fail.
krock
A: 

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.

The Elite Gentleman