You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中ArrayList的retainAll方法困惑:交集操作抛出异常

解决Java集合retainAll()抛出UnsupportedOperationException的问题

嘿,这个坑我之前刚踩过!咱们来一步步捋清楚问题出在哪,以及怎么解决。

问题根源

你用Arrays.asList()创建的列表,并不是我们平时用的java.util.ArrayList,而是Arrays类内部的一个静态内部类java.util.Arrays.ArrayList。这个内部类是基于原始数组实现的,它的设计是固定大小的——只能修改已有元素的值,但不支持添加、删除这类会改变集合结构的操作。

而retainAll()方法的作用是保留两个集合的交集,本质上是要移除原集合中不在目标集合里的元素。当你调用coll1.retainAll(coll2)时,因为coll1是固定大小的列表,尝试移除元素(这里要移除"A")就触发了不支持的操作,所以抛出UnsupportedOperationException。

解决方案

有两种常用的处理方式,看你需求选:

1. 转成可修改的ArrayList

把Arrays.asList()的结果包装成真正的java.util.ArrayList,这样集合就支持结构修改了:

List<String> coll1 = new ArrayList<>(Arrays.asList("A"));
List<String> coll2 = new ArrayList<>(Arrays.asList("B", "C"));
coll1.retainAll(coll2);
System.out.println(coll1); // 输出 [],完全符合预期

2. 用Stream流生成交集(不修改原集合)

如果不想修改原集合,或者只是需要得到交集结果,用Java 8+的Stream API更优雅:

List<String> coll1 = Arrays.asList("A");
List<String> coll2 = Arrays.asList("B", "C");
List<String> intersection = coll1.stream()
                                 .filter(coll2::contains)
                                 .collect(Collectors.toList());
System.out.println(intersection); // 输出 []

这种方式会生成一个新的集合,原集合完全不受影响,也不会有任何异常。

内容的提问来源于stack exchange,提问作者Oliver Watkins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:26:37