Joe
Joe

Reputation: 15359

Concatenating two string arrays throws UnsupportedOperationException

    String[] aArr = ...;
    String[] bArr = ...;

    List<String> images = Arrays.asList(aArr);
    images.addAll(Arrays.asList(bArr));

throws the following exception at addAll and also raises the same exception if you add the elements of the second list individually.

java.lang.UnsupportedOperationException
09:06:57,156 ERROR [STDERR] at java.util.AbstractList.add(AbstractList.java:
131)
09:06:57,156 ERROR [STDERR] at java.util.AbstractList.add(AbstractList.java:
91)

How should I rectify this?

Upvotes: 2

Views: 1047

Answers (2)

MeBigFatGuy
MeBigFatGuy

Reputation: 28598

Arrays.asList(aArr);

returns an immutable list (well, size wise anyway), because the list just refers to the initial array for when you call get(i). so create another one that isn't like this, such as

List<String> images = new ArrayList(Arrays.asList(aArr));

Upvotes: 3

aroth
aroth

Reputation: 54856

Like this:

List<String> images = new ArrayList<String>();
images.addAll(Arrays.asList(aArr));
images.addAll(Arrays.asList(bArr));

Note that as per the documentation, Arrays.asList() returns a fixed-size list. So if you want to concatenate both arrays, you need to allocate your own variable-sized list to do it.

Upvotes: 3

Related Questions