简体   繁体   中英

How to force java to accept the same type generic parameters

I found the following code snippet from 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? say only 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. 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. I've not draw the example of <T extends String> as String class is final .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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