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.
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 returns a fixed-size list that is backed by the specified array; the returned list is serializable and allows random access.
Arrays. asList() , the list is immutable.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With