List.addAll throwing UnsupportedOperationException

2020-01-30 11:47发布

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?

标签: java
5条回答
一夜七次
2楼-- · 2020-01-30 12:19

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.

查看更多
家丑人穷心不美
3楼-- · 2020-01-30 12:31

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.

查看更多
手持菜刀,她持情操
4楼-- · 2020-01-30 12:40

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<>();
查看更多
Ridiculous、
5楼-- · 2020-01-30 12:42

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(",")));
查看更多
趁早两清
6楼-- · 2020-01-30 12:44

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"));

查看更多
登录 后发表回答