79

List.addAll throwing UnsupportedOperationException when trying to add another list.

List<String> supportedTypes = Arrays.asList("6500", "7600"};

and in loop I am doing,

supportedTypes.addAll(Arrays.asList(supportTypes.split(","))); //line 2

reading supportTypes from a file.

But line 2 throws a UnsupportedOperationException, but I am not able to determine why?

I am adding another list to a list, then why this operation is unsupported?

Dexkill
  • 284
  • 1
  • 2
  • 20
codingenious
  • 8,385
  • 12
  • 60
  • 90

5 Answers5

148

Arrays.asList returns a fixed sized list backed by an array, and you can't add elements to it.

You can create a modifiable list to make addAll work :

List<String> supportedTypes = new ArrayList<String>(Arrays.asList("6500", "7600", "8700"));

xsorifc28
  • 5,112
  • 6
  • 16
  • 24
Eran
  • 387,369
  • 54
  • 702
  • 768
  • @Batty - and that is the problem. It doesn't work. The javadoc for `asList` makes it clear that it won't work. End of story. You CANNOT add elements to a list created using `asList`. Period. – Stephen C Sep 02 '14 at 13:17
  • 2
    List is an interface, the current implementation has to implement all its methods, but that implementation can throw an Exception to say "this method has no sense here" – Pablo Lozano Sep 02 '14 at 13:20
22

This error also happens when the list is initialized with Collections.emptyList(), which is immutable:

List<String> myList = Collections.emptyList();

Instead, initialize it with a mutable list. For example

List<String> myList = new ArrayList<>();
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
14

Arrays.asList returns a fixed-size list.

If you to want be able to add elements to the list, do:

List<String> supportedTypes = new ArrayList<>(Arrays.asList("6500", "7600"});
supportedTypes.addAll(Arrays.asList(supportTypes.split(",")));
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
8

Problem is that Arrays.asList method returns instance of java.util.Arrays.ArrayList which doesn't support add/remove operations on elements. It's not surprizing that addAll method throws exception because add method for java.util.Arrays.ArrayList is defined as:

public void add(int index, E element) {
    throw new UnsupportedOperationException();
}

Related question:

Arrays.asList() Confusing source code

From the documentation:

Arrays.asList returns a fixed-size list backed by the specified array.

Community
  • 1
  • 1
bsiamionau
  • 8,099
  • 4
  • 46
  • 73
0

In my case this exception occured when I called adapter.addAll(items), where adapter was a custom ArrayAdapter. This CustomAdapter had a parameter of type Array instead of ArrayList.

CoolMind
  • 26,736
  • 15
  • 188
  • 224