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

Java中Collectors.toList()返回结果如何转LinkedList且不使用toCollection收集器?

java.lang.ClassCastException 异常的根因是 Collectors.toList() 仅约定返回 List 接口的实现,JDK 未规范具体实现类型,目前主流 OpenJDK 版本默认返回 ArrayList,无法直接强转为 LinkedList。

以下是符合要求的可行方案:

  • 方案1:修改随机数生成方法的返回值类型为 LinkedList<Integer>,方法内部完成类型封装,外部无需额外处理
// fillRandom类修改后代码
import java.util.LinkedList;
import java.util.Random;

public class fillRandom {
    public static LinkedList<Integer> IntFill(){
        LinkedList<Integer> res = new LinkedList<>();
        new Random().ints(10,0,100).forEach(res::add);
        return res;
    }
}

调用侧代码:

public class Main {
    public static void main(String[] args) throws Exception {
        LinkedList<Integer> linkedList = fillRandom.IntFill();
        Print printer = new printImpl();
        printer.print(linkedList);
    }
}
  • 方案2:不改动fillRandom类的原有定义,调用侧通过LinkedList的带参构造函数接收返回的List集合完成初始化
public class Main {
    public static void main(String[] args) throws Exception {
        List<Integer> linkedList = new LinkedList<>(fillRandom.IntFill());
        Print printer = new printImpl();
        printer.print(linkedList);
    }
}
  • 方案3:完全规避Stream collect操作,手动生成随机数写入LinkedList
// fillRandom类IntFill方法修改后代码
public static LinkedList<Integer> IntFill(){
    LinkedList<Integer> res = new LinkedList<>();
    Random random = new Random();
    for (int i = 0; i < 10; i++) {
        res.add(random.nextInt(100));
    }
    return res;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:39:03