Operation exception: java.lang.UnsupportedOperationException List.remove/add method reports an error

1. Problem presentation 

When deleting a list data (List<String>), an error java.lang.UnsupportedOperationException is reported.

2. The cause of the problem

1. Click on the error report and find that there are two packages: a, java.util.ArrayList package; b, java.util.Arrays.ArrayList package (key point)

2. Calling the add and remove methods of the List produced by Arrays.asList() reports an exception. This is because Arrays.asList() returns the internal class ArrayList of Arrays, not java.util.ArrayList.

3. Using the asList method to inherit the add and remove of the parent class will only throw an UnsupportedOperationException exception, and java.util.ArrayList rewrites the add and remove of the parent class

4. Therefore, ArrayList is required to use the add()/remove method correctly.

Error code:

if (bean?.playlist?.contains(condition) == true)bean.playlist?.remove(condition)
//bean?.playlist是一个String类型的List列表,当列表里含有此string时,把它移出掉

Modified code:

if (bean?.playlist?.contains(condition) == true){
                    val a = bean.playlist.toMutableList()//直接给他转一下
                    a.remove(condition)
                    bean.playlist = a
                }

Guess you like

Origin blog.csdn.net/LoveFHM/article/details/129705726