[英]How to force java to accept the same type generic parameters
I found the following code snippet from The Java™ Tutorials Type Inference 我从The Java™Tutorials Type Inference中找到了以下代码片段
static <T> T pick(T a1, T a2) { return a2; }
Serializable s = pick("d", new ArrayList<String>());
So a1
and a2
can be different type here, how can I force them to be the same type? 所以
a1
和a2
在这里可以是不同的类型,我怎么能强迫它们是同一类型? say only pick("d", "e");
说只
pick("d", "e");
can be called. 可以叫。
how can I force them to be the same type?
If T is very specific type like only String
, then one simply can avoid generic. 如果T是非常特定的类型,只有
String
,那么就可以避免泛型。 But you can restrict there scope, like - 但你可以限制范围,如 -
static <T extends Number> T pick(T a1, T a2) { return a2; }
pick(0, 1)
, As T is restricted to Number and sub classes. pick(0, 1)
,因为T仅限于Number和sub类。 I've not draw the example of <T extends String>
as String
class is final
. 我没有画出
<T extends String>
的例子,因为String
类是final
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.