Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Arrays.asList return a fixed-size List?

Tags:

java

list

Arrays.asList is a useful and convenient method, but it returns a List whose size is fixed, such that no elements can be added or removed with add or remove (UnsupportedOperationException is thrown).

Is there a good reason for that? It looks like an odd restriction to me.

The documentation does not explain the reason behind it:

Returns a fixed-size list backed by the specified array.

like image 986
Maljam Avatar asked May 03 '16 19:05

Maljam


People also ask

Is array asList fixed-size?

asList is really just reflecting that Java arrays are fixed-size, too. You can't add or remove elements from the backing array, either. As mentioned in the comments, it's quite easy to get a variable-size list from an array with e.g. new ArrayList<>(Arrays.

What does array asList return?

asList returns a fixed-size list that is​ backed by the specified array; the returned list is serializable and allows random access.

Does array asList return immutable list?

Arrays. asList() , the list is immutable.

What does arrays asList () do?

The asList() method of java. util. Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.


1 Answers

The point is that Arrays.asList is returning a view of the array, and that changes to the array are reflected in the List and vice versa. It's not making a copy, it's just a very simple implementation of the List interface that interprets the specified array as a List. As a result, Arrays.asList is really just reflecting that Java arrays are fixed-size, too. You can't add or remove elements from the backing array, either.

As mentioned in the comments, it's quite easy to get a variable-size list from an array with e.g. new ArrayList<>(Arrays.asList(array)).

Also, for what it's worth: Guava actually regrets providing a "resizable list from varargs arguments" method after discovering that most people who used it actually really wanted an immutable list.

like image 125
Louis Wasserman Avatar answered Sep 28 '22 03:09

Louis Wasserman