Reputation: 28
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
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