UnsupportedOperationException

UnsupportedOperationException

This question already has answers here:
Why do I get an UnsupportedOperationException when trying to remove an element from a List?
                                
                                    (16个答案)
                                
                        
                                去年关闭。
            
                    
当我尝试使用removeIf()从列表中删除元素时,它抛出UnsupportedOperationException

public class T {
        public static void main(String[] args) {
        String[] arr = new String[] { "1", "2", "3" };
        List<String> stringList = Arrays.asList(arr);
        stringList.removeIf((String string) -> string.equals("2"));
    }
}


有人可以帮助我了解为什么会这样吗,我该如何纠正?

最佳答案

Arrays.asList(arr)返回固定大小的List,因此您不能从中添加或删除元素(只能替换现有元素)。

创建一个ArrayList代替:

List<String> stringList = new ArrayList<>(Arrays.asList(arr));

09-05 15:24