java.lang.UnsupportedOperationException at java.util.AbstractLis

本文探讨了在尝试从不可变列表中移除元素时遇到的 UnsupportedOperationException 异常。通过分析 Arrays.asList() 的行为,解释了它返回的是不可变列表,并提出了两种解决方案:一是将列表转换为 ArrayList,二是使用迭代器进行元素移除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天写个代码简化后如下 竟然发生如题的错误

public void do(List rs){
rs.remove("a");
}

明明记得 传进来的rs是一个ArrayList。
仔细查了前面的代码

List rs =Arrays.asList(new String[]{"a","c"});
do(rs);


仔细一查javadoc
When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList which is an immutable list. You cannot add to it and you cannot remove from it.

If you want a mutable list built from your array you will have to loop over the array yourself and add each element into the list in turn.

Even then your code won't work because you'll get an IndexOutOfBoundsException as you remove the elements from the list in the for loop. There are two options: use an Iterator which allows you to remove from the list as you iterate over it (my recommendation as it makes the code easier to maintain) or loop backwards over the loop removing from the last one downwards (harder to read).

You are using AbstractList. ArrayList and Arrays$ArrayList are both types of AbstractList. That's why you get UnsupportedOperationException: Arrays$ArrayList does not override remove(int) so the method is called on the superclass, AbstractList, which is what is throwing the exception because this method is not implemented on that class (the reason being to allow you to build immutable subclasses)


解决方法是使用循环 add();

或者转换为ArrayList
[code]
List list = Arrays.asList(a[]);
List arrayList = new ArrayList(list);
[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值