Java中的这种泛型用法是什么? X.< Y>()的方法 [英] What's this generics usage in Java? X.<Y>method()

查看:80
本文介绍了Java中的这种泛型用法是什么? X.< Y>()的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过整本SCJP6书中的塞拉利昂和贝茨的书,考了88%。但是,我还没听说过这种代码是如何工作的因为它在泛型章节中没有解释:

  Collections。< TimeUnit> reverseOrder()

这种泛型用法是什么?
我在一些代码中发现了它,但从未读过任何关于它的东西。
在我看来,它可以给键入推理提供一些帮助。
我试过寻找那个,但它不是很容易找到(甚至在SCJP书籍/考试中也没有!)

给我一个关于它是如何工作的正确解释,哪些是所有的用例等等?

谢谢




编辑
感谢您的答案,但我期望得到更多详细信息:)所以如果有人想添加一些额外的信息:



更复杂的情况怎么样?


  • 使用类中声明的类型,我可以像 Collections。< T> reverseOrder() for example

  • 使用 extends super

  • 使用
  • >赋予编译器仅部分帮助(即 O.manyTypesMethod <?,MyHelpTypeNotInfered,?,?,?,?>>()

解决方案

它是泛型方法的显式类型说明。你可以随时做到,但在大多数情况下不需要。但是,在某些情况下,如果编译器无法自行推断泛型类型,则需要它。



查看教程页面

更新:只有你的第一个例子是有效的。显式类型参数必须是显式的,所以不允许有通配符 extends super 。此外,无论是明确指定每个类型参数,还是不指定它们;即显式类型自变量的数量必须与被调用方法的类型参数的数量相匹配。如果在当前范围内定义良好,则允许诸如 T 的类型参数,例如,作为封闭类的类型参数。


I've read the whole SCJP6 book Sierra and Bates book, scored 88% the exam.

But still, i never heard of how this kind of code works as it's not explained in the generics chapter:

Collections.<TimeUnit>reverseOrder()

What is this kind of generics usage? I discovered it in some code but never read anything about it. It seems to me it permits to give some help to type inference. I've tried to search about that but it's not so easy to find (and it's not even in the SCJP book/exam!)

So can someone give me a proper explaination of how it works, which are all the usecases etc?

Thanks


Edit Thanks for the answers but i expected more details :) so if someone want to add some extra informations:

What about more complex cases like

  • Using a type declared in class , can i do something like Collections.<T>reverseOrder() for exemple?
  • Using extends, super?
  • Using ?
  • Giving the compiler only partial help (ie O.manyTypesMethod<?,MyHelpTypeNotInfered,?,?,?,?,?>() )

解决方案

It is explicit type specification of a generic method. You can always do it, but in most cases it's not needed. However, it is required in some cases if the compiler is unable to infer generic type on its own.

See an example towards the end of the tutorial page.

Update: only the first of your examples is valid. The explicit type argument must be, well, explicit, so no wildcards, extends or super is allowed there. Moreover, either you specify each type argument explicitly or none of them; i.e. the number of explicit type arguments must match the number of type parameters of the called method. A type parameter such as T is allowed if it is well defined in the current scope, e.g. as a type parameter of the enclosing class.

这篇关于Java中的这种泛型用法是什么? X.&LT; Y&GT;()的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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