为什么在不使用泛型的汽化列表上使用收集后返回对象?

问题描述 投票:0回答:1

为什么下面的代码生成一个对象而不是列表?

Object listWithoutGeneric = new ArrayList().stream().collect(Collectors.toList());

(试图用List listWithoutGeneric = ...替换为Object listWithoutGeneric = ...产生编译错误)

以下示例返回列表时?

List listWithDefaultGeneric = new ArrayList<>().stream().collect(Collectors.toList());
java generics steam
1个回答
0
投票

您的终端操作-collect-具有以下签名:

<R, A> R collect(Collector<? super T, A, R> collector)

即它返回类型为R的实例。

[toList() Collector返回Collector<T, ?, List<T>>,因此在这种情况下,RList<T>

但是,如果要从原始Stream创建ArrayList,则Stream也是原始的,因此R变为Object

© www.soinside.com 2019 - 2024. All rights reserved.