Jin Tim
Jin Tim

Reputation: 28

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.

Upvotes: 1

Views: 100

Answers (1)

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

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.

Upvotes: 3

Related Questions