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 方法。

相关推荐
这周也會开心4 分钟前
云服务器安装JDK、Tomcat、MySQL
java·服务器·tomcat
hrrrrb1 小时前
【Spring Security】Spring Security 概念
java·数据库·spring
小信丶1 小时前
Spring 中解决 “Could not autowire. There is more than one bean of type“ 错误
java·spring
sdgsdgdsgc1 小时前
Next.js企业级应用开发:SSR、ISR与性能监控方案
开发语言·前端·javascript
周杰伦_Jay2 小时前
【Java虚拟机(JVM)全面解析】从原理到面试实战、JVM故障处理、类加载、内存区域、垃圾回收
java·jvm
rit84324995 小时前
基于MATLAB的模糊图像复原
开发语言·matlab
fie88895 小时前
基于MATLAB的声呐图像特征提取与显示
开发语言·人工智能
程序员小凯5 小时前
Spring Boot测试框架详解
java·spring boot·后端
豐儀麟阁贵6 小时前
基本数据类型
java·算法
_extraordinary_6 小时前
Java SpringMVC(二) --- 响应,综合性练习
java·开发语言