1

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.

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answering but I can still call like this pick(1,1.0); Maybe java doesn't support this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.