Generic methods
40 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A generic method declares its own type parameter, written just before the return type: static <T> T firstOf(T[] items). One method then works for a String[], an Integer[] or a Product[], with full type checks and no casts.
A method with its own type parameter
A generic method is a method that declares its own type parameters in angle brackets before its return type, like static <T> void printAll(T[] items). The type is chosen again at every call, and the method can be generic even when its class is not.
An online store prints its product names, prices and seller grades from three arrays of three types. Three print methods would repeat the same loop. Put <T> before the return type, and one method serves every array.
Example 1 · One print method for every array
public class PrintAllDemo { static <T> void printAll(String title, T[] items) { System.out.print(title + ":"); for (T item : items) { System.out.print(" " + item); } System.out.println(); }
public static void main(String[] args) { String[] catalog = { "Keyboard", "Camera", "Mouse" }; Integer[] prices = { 2000, 6000, 500 }; Character[] grades = { 'A', 'B', 'A' };
printAll("Catalog", catalog); printAll("Prices", prices); printAll("Grades", grades); }}Catalog: Keyboard Camera Mouse Prices: 2000 6000 500 Grades: A B A
What this code does
<T>beforevoiddeclares the method's own type parameter;T[] itemsandT itemthen use it.PrintAllDemoitself is not generic: an ordinary class can have generic methods.- Each call picks its own
T:String, thenInteger, thenCharacter.
Read the header from left to right: static, then <T> ("this method has a type parameter T"), then the return type, the name and the parameters. The <T> must come before the return type, even when the return type is void.
Type inference: the compiler works out T
Type inference is the Java compiler (javac) working out the type arguments by itself, from the arguments of a call and the type the result is assigned to. In firstOf(catalog) with a String[] catalog, the Java compiler infers T = String, so you rarely write the type yourself.
None of the calls above says T = String. The Java compiler looks at each argument, matches it against T[] and decides what T must be for that call. The return type then follows from T.
Example 2 · firstOf, lastOf and indexOf for any array
class ArrayUtil { static <T> T firstOf(T[] items) { return items[0]; }
static <T> T lastOf(T[] items) { return items[items.length - 1]; }
static <T> int indexOf(T[] items, T target) { for (int i = 0; i < items.length; i++) { if (items[i].equals(target)) { return i; } } return -1; }}
public class InferenceDemo { public static void main(String[] args) { String[] catalog = { "Keyboard", "Camera", "Mouse", "Laptop" }; Integer[] tickets = { 101, 102, 103 };
String first = ArrayUtil.firstOf(catalog); Integer last = ArrayUtil.lastOf(tickets); System.out.println("First product: " + first + ", last ticket: " + last); System.out.println("Mouse is at index " + ArrayUtil.indexOf(catalog, "Mouse")); System.out.println("Ticket 110 is at index " + ArrayUtil.indexOf(tickets, 110)); System.out.println("Explicit: " + ArrayUtil.<String>firstOf(catalog)); }}First product: Keyboard, last ticket: 103 Mouse is at index 2 Ticket 110 is at index -1 Explicit: Keyboard
What this code does
firstOf(catalog)infersT = String, so the result goes straight into aString;lastOf(tickets)infersInteger.indexOfusesTtwice, for the array and the target, and compares withequals, as in The equals() method (opens in a new tab).ArrayUtil.<String>firstOf(catalog)writes the type argument by hand. It is legal, but inference makes it rarely needed.
Order of execution
What the Java compiler does with firstOf(catalog)
Tap the steps in the order the Java compiler does them.
T[] needs an array of objects
Autoboxing turns one int into an Integer, but it never turns a whole int[] into an Integer[]. So a T[] parameter cannot take an int[].
Example 3 · int[] is not a T[]
public class IntArrayDemo { static <T> T firstOf(T[] items) { return items[0]; }
public static void main(String[] args) { int[] prices = { 2000, 6000, 500 }; System.out.println(firstOf(prices)); }}IntArrayDemo.java:8: error: method firstOf in class IntArrayDemo cannot be applied to given types;
System.out.println(firstOf(prices));
^
required: T[]
found: int[]
reason: inference variable T has incompatible bounds
equality constraints: int
upper bounds: Object
where T is a type-variable:
T extends Object declared in method <T>firstOf(T[])
1 errorWhat this code does
Tcan only be an object type, soT[]means an array of objects.int[]is an array of primitives and matches noT[].- The reason lines say it:
Twould have to beint(the equality constraint), but everyTmust be an object type (the upper boundObject). - The fix is
Integer[] prices = { 2000, 6000, 500 };: each value is autoboxed as the array is built.
Most real code avoids the problem by using lists, which hold objects anyway: the Lists module (opens in a new tab) uses ArrayList<Integer> for numbers.
Static methods and the class's type parameter
A generic factory method is a static generic method that creates and returns an object of a generic class, like static <A, B> Pair<A, B> of(A first, B second). It declares its own type parameters, because a static method cannot use the class's.
A class's K and V belong to each object: one Pair is a Pair<String, Integer>, another a Pair<Integer, String>. A static method runs without any object, so it declares type parameters of its own.
Example 4 · A static factory method: Pair.of
class Pair<K, V> { private K first; private V second;
Pair(K first, V second) { this.first = first; this.second = second; }
static <A, B> Pair<A, B> of(A first, B second) { return new Pair<>(first, second); }
K getFirst() { return first; }
V getSecond() { return second; }}
public class FactoryDemo { public static void main(String[] args) { Pair<String, Integer> bundle = Pair.of("Headphones + USB hub", 9500); Pair<Integer, String> ticket = Pair.of(17, "Priya"); System.out.println(bundle.getFirst() + ": Rs. " + bundle.getSecond()); System.out.println("Ticket " + ticket.getFirst() + ": " + ticket.getSecond()); }}Headphones + USB hub: Rs. 9500 Ticket 17: Priya
What this code does
static <A, B> Pair<A, B> of(A first, B second)declares two type parameters of its own and returns aPairbuilt from them.Pair.of("Headphones + USB hub", 9500)infersA = StringandB = Integerfrom the arguments: no<>, no type written anywhere on the right side.
The <A, B> of of are new names on purpose: they are the method's own, separate from the class's K and V. Java's own library is full of such factories, for example List.of(...) in the Lists module.
Fix the error
Fix the generic method header
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
A static helper in Box<T> returns the first value that is not null.
Error
Box.java:2: error: non-static type variable T cannot be referenced from a static context
static T pick(T a, T b) {
^Example 5 · Find the best item with a rule passed in
interface Better<T> { boolean isBetter(T a, T b);}
class Product { String name; int price;
Product(String name, int price) { this.name = name; this.price = price; }}
public class BestDemo { static <T> T best(T[] items, Better<T> rule) { T winner = items[0]; for (T item : items) { if (rule.isBetter(item, winner)) { winner = item; } } return winner; }
public static void main(String[] args) { Product[] catalog = { new Product("Headphones", 6000), new Product("Keyboard", 2000), new Product("Monitor", 11000) }; String[] products = { "Laptop", "Smartwatch", "Wireless charger" };
Product cheapest = best(catalog, (a, b) -> a.price < b.price); Product costliest = best(catalog, (a, b) -> a.price > b.price); String longest = best(products, (a, b) -> a.length() > b.length());
System.out.println("Cheapest: " + cheapest.name + ", Rs. " + cheapest.price); System.out.println("Costliest: " + costliest.name + ", Rs. " + costliest.price); System.out.println("Longest name: " + longest); }}Cheapest: Keyboard, Rs. 2000 Costliest: Monitor, Rs. 11000 Longest name: Wireless charger
What this code does
Better<T>is a generic interface with one method, so a lambda can implement it, as in Functional interfaces and lambdas (opens in a new tab).- In
best(catalog, (a, b) -> a.price < b.price), the Java compiler infersT = Productfromcatalog, soaandbareProductobjects anda.pricecompiles. - One generic method answers three questions; only the rule changes.
Next step
Check your understanding
12 quick questions