Half Blood Prince
Half Blood Prince

Reputation: 1111

Java - Difference between fixed-sized list and list with initial capacity specified

I am having an issue in understanding this.

while we do

 List<Integer> list = Arrays.asList(array);

we can not use methods like add, remove on that list. I know that Arrays.asList() returns a fixed-sized list.

What I don't understand is if we create a list with initial capacity specified like

List<Integer> list2 = new ArrayList<Integer>(10);

we can perform all the operations on that list. What is the difference between fixed-sized list and list with initial capacity specified?

I have read many answers on this but having such a hard time understanding this. Can anyone explain?

Thanks.

Upvotes: 2

Views: 336

Answers (2)

Dunes
Dunes

Reputation: 40903

Very simply, Arrays.asList is so you can use List methods with an array. ArrayList(int) is for when you need to create a really large ArrayList and want to help speed things up a bit.

In more detail: the List returned by asList is intended as a wrapper to an array. Since you cannot resize an array, the methods that change the size of a List are unimplemented. Most of the time I just use asList to add a fixed number of elements to a collection simply. eg.

new ArrayList<String>(Arrays.asList("hello", "world"));

Confusingly, the implementation of ArrayList is very similar -- it's a List backed by an array. However, ArrayList allows you to change it's size. To do this it keeps a separate fields about the how many objects are in the list and the length of the backing array. Add an element and the ArrayList just sets array[size] to the element and then increments the size field. But what if array[size] is out of bounds? At this point the ArrayList creates a new, larger array and copies over the elements from the previous backing array. However, if you are creating a large List then this constant creation of new backing arrays can start to take up a lot of time. As such, if you know the approximate number of elements that will be in the List you can use this to inform the ArrayList about the size of the initial backing array it should create. This is what the ArrayList(int) constructor is for. Only in exceptional circumstances will you need to worry about giving the ArrayList a length hint.

Upvotes: 4

Vikas Singh
Vikas Singh

Reputation: 3038

Arrays.asList(array) returns an object of type java.util.Arrays.ArrayList, which does not support add and remove operations.

While the code below will return an object of type java.util.ArrayList, which supports add and remove operations.

List<Integer> list2 = new ArrayList<Integer>(10);`

Upvotes: 5

Related Questions