AutoMEta
AutoMEta

Reputation: 1351

object storage capacity Array list

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?

Upvotes: 1

Views: 217

Answers (4)

krock
krock

Reputation: 29619

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

Upvotes: 1

Buhake Sindi
Buhake Sindi

Reputation: 89169

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.

Upvotes: 0

InsertNickHere
InsertNickHere

Reputation: 3666

The capacity of the ArrayList will be increased by ensureCapacity.

Upvotes: 0

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

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.

Upvotes: 1

Related Questions