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

Java调用Collections.sort()抛出UnsupportedOperationException原因咨询

问题原因与解决方案

异常触发原因

你调用Collections.sort()时抛出UnsupportedOperationException,核心问题出在列表的可变性上:

  • Java 16及以上版本中,Stream.toList()方法返回的是不可变列表(具体实现为ImmutableCollections包下的内部类)。
  • Collections.sort()需要对列表进行原地修改(调整元素顺序),但不可变列表不支持任何修改其结构或元素顺序的操作,因此直接触发异常。

从错误栈也能得到验证:异常起源于java.base/java.util.ImmutableCollections.uoe,uoe正是UnsupportedOperationException的缩写,明确指向不可变集合的限制。

修复方案

可以通过以下两种方式获取可变列表,从而支持排序、反转等操作:

  1. 将不可变列表包装为可变的ArrayList:
    List<Integer> convList = new ArrayList<>(Arrays.stream(arr).boxed().toList());
    
  2. 使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 07:03:31