1

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?

Cœur
39k25 gold badges206 silver badges281 bronze badges
asked Aug 12, 2010 at 10:03

4 Answers 4

1

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

answered Aug 12, 2010 at 10:06

2 Comments

so is it done automatically or we have to make sure it happens??
if you use the 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.
1

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.

answered Aug 12, 2010 at 10:06

Comments

0

The capacity of the ArrayList will be increased by ensureCapacity.

answered Aug 12, 2010 at 10:06

Comments

0

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.

answered Aug 12, 2010 at 10:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.