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

【电子书大全】内含上千本顶级编程书籍,是程序员必备的电子书资源包,并且会不断地更新,现免费分享给大家,助你在编程的道路上更上一层楼!

链接: https://pan.baidu.com/s/1yhPJ9LmS_z5TdgIgxs9NvQ?pwd=yyds > 提取码: yyds

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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值