Command Palette

Search for a command to run...

Back to the lesson: Topic 8.3 — Generic Methods
Core Java · Example 2 of 4

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.

01

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.

02

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.

03

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

01

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?

02

Explain type inference. What information does the compiler use to decide T?

03

What is a type witness, and when would you use one?

04

Why are generic static factory methods so common in the JDK?

Inference: from arguments, from the target, and by witness
Sign in to run this example in your browser.

Expected output

pick strings: chai
pick mixed: 42 (Integer)
as Comparable: 42
empty: []
count: 0
witnessed: 0