2

I want to instantiate an ArrayList of ArrayLists (of a generic type). I have this code:

private ArrayList<ArrayList<GameObject>> toDoFlags;
toDoFlags = new ArrayList<ArrayList<GameObject>>(2);

Am I doing this right? It compiles, but when I look at the ArrayList, it has a size of 0.

2 Answers 2

6

You're doing it right. The reason it has zero length is because you haven't added anything to it yet.

The "2" you pass is the initial capacity of the array that backs the ArrayList. But the size() method of the ArrayList doesn't return the initial capacity of its backing array... it returns the number of actual elements in the list.

Customarily, you shouldn't be using the initialCapacity parameter. It's a performance optimization when you have large ArrayLists. By allocating a lot of space explicitly, you save the time it would take to re-allocate as you add more and more items to the list. But in this case you probably don't have an extremely large list.

Also, instead of using an ArrayList of ArrayLists, you should consider writing a class to store your data.

Sign up to request clarification or add additional context in comments.

1 Comment

To add to this, the (2) at the end just allocates space for two objects in the list. I imagine that's where the confusion was coming from.
1

ArrayLists expand as you add to them. The integer capacity argument just sets the initial size of the backing array. Setting the capacity to two doesn't mean that there are two elements in the ArrayList, but rather that two elements can be added to the ArrayList before it has to declare a larger internal array.

Comments

Your Answer

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.