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

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

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

原因

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

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

解决方案

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

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

示例代码

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

java 复制代码
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 方法。

相关推荐
重生之我要进大厂12 分钟前
LeetCode 876
java·开发语言·数据结构·算法·leetcode
_祝你今天愉快15 分钟前
技术成神之路:设计模式(十四)享元模式
java·设计模式
Amo Xiang28 分钟前
Python 常用模块(四):shutil模块
开发语言·python
Happy鱿鱼1 小时前
C语言-数据结构 有向图拓扑排序TopologicalSort(邻接表存储)
c语言·开发语言·数据结构
KBDYD10101 小时前
C语言--结构体变量和数组的定义、初始化、赋值
c语言·开发语言·数据结构·算法
计算机学姐1 小时前
基于python+django+vue的影视推荐系统
开发语言·vue.js·后端·python·mysql·django·intellij-idea
小筱在线1 小时前
SpringCloud微服务实现服务熔断的实践指南
java·spring cloud·微服务
luoluoal1 小时前
java项目之基于Spring Boot智能无人仓库管理源码(springboot+vue)
java·vue.js·spring boot
ChinaRainbowSea1 小时前
十三,Spring Boot 中注入 Servlet,Filter,Listener
java·spring boot·spring·servlet·web
Crossoads1 小时前
【数据结构】排序算法---桶排序
c语言·开发语言·数据结构·算法·排序算法