Java调用Collections.sort()抛出UnsupportedOperationException原因咨询
问题原因与解决方案
异常触发原因
你调用Collections.sort()时抛出UnsupportedOperationException,核心问题出在列表的可变性上:
- Java 16及以上版本中,
Stream.toList()方法返回的是不可变列表(具体实现为ImmutableCollections包下的内部类)。 Collections.sort()需要对列表进行原地修改(调整元素顺序),但不可变列表不支持任何修改其结构或元素顺序的操作,因此直接触发异常。
从错误栈也能得到验证:异常起源于java.base/java.util.ImmutableCollections.uoe,uoe正是UnsupportedOperationException的缩写,明确指向不可变集合的限制。
修复方案
可以通过以下两种方式获取可变列表,从而支持排序、反转等操作:
- 将不可变列表包装为可变的
ArrayList:List<Integer> convList = new ArrayList<>(Arrays.stream(arr).boxed().toList()); - 使用
Collectors类的方法生成可变列表:// 使用Collectors.toList()生成可变列表 List<Integer> convList = Arrays.stream(arr).boxed().collect(Collectors.toList()); // 或者明确指定生成ArrayList List<Integer> convList = Arrays.stream(arr).boxed().collect(Collectors.toCollection(ArrayList::new));
修改后,Collections.sort()和Collections.reverse()即可正常执行。
内容的提问来源于stack exchange,提问作者Goutham
相关产品推荐
相关产品推荐

