自学内容网 自学内容网

Arrays.asList()创建的集合不能使用remove函数

Arrays.asList() 创建的集合确实不能直接使用 remove 方法,这是因为该方法返回的集合是一个固定大小的列表,背后由一个数组支持。由于数组的长度是固定的,所以这个列表也不能增加或减少元素。

以下是详细解释和解决方案:

原因

Arrays.asList() 返回的是一个内部类 java.util.Arrays.ArrayList 的实例,它是一个固定大小的列表,不支持添加或删除元素操作。尝试调用 remove 方法会抛出 UnsupportedOperationException

List<String> list = Arrays.asList("a", "b", "c");
list.remove("a"); // 抛出 UnsupportedOperationException

解决方案

如果需要一个可以自由增删元素的列表,可以将 Arrays.asList() 返回的固定大小列表转换成一个可变的列表,例如 ArrayList

1. 使用 ArrayList 构造函数
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
list.remove("a"); // 成功
2. 使用 Collections.addAll()
List<String> list = new ArrayList<>();
Collections.addAll(list, "a", "b", "c");
list.remove("a"); // 成功
3. 使用 Stream API(Java 8 及以上)
List<String> list = Arrays.stream(new String[]{"a", "b", "c"})
                          .collect(Collectors.toCollection(ArrayList::new));
list.remove("a"); // 成功

示例代码

以下是一个完整的示例,展示如何将 Arrays.asList() 返回的固定大小列表转换为一个可变的列表,然后进行删除操作:

import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        // 使用 Arrays.asList() 创建固定大小的列表
        List<String> fixedList = Arrays.asList("a", "b", "c");

        // 方法1:使用 ArrayList 构造函数
        List<String> mutableList1 = new ArrayList<>(fixedList);
        mutableList1.remove("a");
        System.out.println(mutableList1); // 输出: [b, c]

        // 方法2:使用 Collections.addAll()
        List<String> mutableList2 = new ArrayList<>();
        Collections.addAll(mutableList2, "a", "b", "c");
        mutableList2.remove("a");
        System.out.println(mutableList2); // 输出: [b, c]

        // 方法3:使用 Stream API
        List<String> mutableList3 = Arrays.stream(new String[]{"a", "b", "c"})
                                          .collect(Collectors.toCollection(ArrayList::new));
        mutableList3.remove("a");
        System.out.println(mutableList3); // 输出: [b, c]
    }
}

通过这些方法,你可以创建一个可以自由增删元素的列表,并且安全地使用 remove 方法。


原文地址:https://blog.csdn.net/chaogu94/article/details/140689831

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!