Reputation: 1214
I have a question regarding the use of a List after it has bee created. I am getting an java.lang.UnsupportedOperationException in the following snippet. Any ideas?
List <Integer> aList = Arrays.asList(3, 4);
if (condition)
aList.add(5);
This doesn't work either
aList.add(new Integer(5));
I want to initialize a list with common values then add conditional ones.
Upvotes: 0
Views: 118
Reputation: 15418
As per the documentation: the asList(T...)
function returns a fixed size list backed by the specified array.
the returned list doesn't have a add(E element)
function implementation referring to the source.
You will need to do:
ArrayList<Integer>aList = new ArrayList<>(Arrays.asList(3, 4));
Upvotes: 0
Reputation: 22715
Arrays.asList returns a fixed-size array, you can't add to it. See api.
Upvotes: 1
Reputation: 44444
From the docs,
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.
The list returned does not support addition of new element.
Upvotes: 1
Reputation: 691865
From the javadoc:
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)
(emphasis mine)
If you want a List that can resize, use
new ArrayList<>(Arrays.asList(3, 4));
Upvotes: 2