Collectors.toList()返回的收集器类型 [英] Type of Collector returned by Collectors.toList()

查看:2307
本文介绍了Collectors.toList()返回的收集器类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Collectors.toList()和Collectors.toSet()静态方法感到很困惑。这两种方法不接受任何参数。那么他们如何知道要返回哪种类型的收藏家?



例如,如果我们有这一行:

  Collectors.toList(); 

返回的收集器是收集器<对象,?,列表<对象>> ;



如果我们有这一行:

 集电极<整数,列表与LT;整数>> c = Collectors.toList(); 

然后Collectors.toList()将返回收集器<整数,?,列表与LT;整数>> 。如果不接受任何输入参数,toList()方法如何知道它需要返回 Collector< Integer,?,List< Integer>>



也许编写toList()的示例代码对我的理解很有帮助。



提前致谢。<这是以目标类型


Java编译器利用目标类型来推断泛型方法调用的类型参数。表达式的目标类型是Java编译器所期望的数据类型,具体取决于表达式的出现位置。


例如:

  // v ---通用参数`T`由目标类型推断
收集器<整数,?,列表与LT;整数>> c = Collectors.toList();

// v --- unbounded类型参数是扩展`Object`
Collectors.toList();


I am quite puzzled about the Collectors.toList() and Collectors.toSet() static methods. These two methods do not take in any parameters. So how do they know what types of Collector to return?

For example, if we have this line:

Collectors.toList();

The returned Collector is Collector<Object,?,List<Object>>.

If we have this line:

Collector<Integer,?,List<Integer>> c = Collectors.toList();

Then Collectors.toList() will return a Collector<Integer,?,List<Integer>>. Without taking in any input parameters, how does the toList() method know that it needs to return a Collector<Integer,?,List<Integer>>?

Perhaps a sample codes of how toList() is written would be helpful in my understanding.

Thanks in advance.

解决方案

This feature is introduced as target type in generic type inference.

The Java compiler takes advantage of target typing to infer the type parameters of a generic method invocation. The target type of an expression is the data type that the Java compiler expects depending on where the expression appears.

For example:

//         v--- the generic parameter `T` is inferred by the target type 
Collector<Integer,?,List<Integer>> c = Collectors.toList();

//         v--- the unbounded type parameter is extends `Object`
Collectors.toList();

这篇关于Collectors.toList()返回的收集器类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆