Multiple Type Parameters in Methods
What you'll learn: How to declare methods that work with two or more different generic types at once.
Just like classes can have multiple type parameters (like Map<K, V>), methods can too. This lets you write flexible methods that handle several different types simultaneously without losing type safety.
The Syntax
You declare multiple type parameters in a comma-separated list between angle brackets, placed before the return type:
public <T, U> void printPair(T first, U second) {
System.out.println("First: " + first + ", Second: " + second);
}
Notice the <T, U> before void. This tells Java that T and U are type parameters for this method specifically.
Using Different Types Together
Multiple type parameters shine when you need to work with values of different types in the same operation:
public <T, U> U convert(T input, U defaultValue) {
if (input == null) {
return defaultValue;
}
// Perform some conversion logic
return defaultValue;
}
// Type inference figures out T=String and U=Integer
Integer result = convert("test", 42);
Real-World Example
public <K, V> void addToMap(K key, V value, Map<K, V> map) {
map.put(key, value);
System.out.println("Added: " + key + " -> " + value);
}
// Java infers K=String, V=Integer
addToMap("age", 25, myMap);
Each type parameter can appear multiple times in the parameter list and return type, providing consistent type checking throughout the method.
Key Takeaway: Multiple type parameters like <T, U> let methods work with several distinct types simultaneously while maintaining full compile-time type safety.