简体   繁体   English

如何强制java接受相同类型的泛型参数

[英]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? 所以a1a2在这里可以是不同的类型,我怎么能强迫它们是同一类型? 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM