glez
glez

Reputation: 1214

Add Element to Initialized Array List

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

Answers (4)

Sage
Sage

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

Jops
Jops

Reputation: 22715

Arrays.asList returns a fixed-size array, you can't add to it. See api.

Upvotes: 1

UltraInstinct
UltraInstinct

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

JB Nizet
JB Nizet

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

Related Questions