Inference: from arguments, from the target, and by witness
The object returned is still the real Integer 42. Inference only decides which static type the compiler lets you treat it as.
A generic method declares its own type parameters, written before the return type: static <T> T first(List<T> list). The compiler works out T from the arguments and the target at each call, so one method serves every type with full checking.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write static <T> int countMatches(List<T> list, T target) that counts elements equal to target using equals. Test it with strings and with integers.
Write static <K, V> Map<V, K> invert(Map<K, V> map) that swaps keys and values, returning a TreeMap. Invert {a=1, b=2, c=3} and print it.
Write static <T> List<T> interleave(List<T> a, List<T> b) that alternates elements from both lists (then appends any leftovers). Test with [1, 3, 5, 7] and [2, 4].
Explain it without notes
How do you declare a generic method, and how is it different from a method in a generic class that uses the class's T?
Explain type inference. What information does the compiler use to decide T?
What is a type witness, and when would you use one?
Why are generic static factory methods so common in the JDK?
Expected output
pick strings: chai
pick mixed: 42 (Integer)
as Comparable: 42
empty: []
count: 0
witnessed: 0