Declaring Generic Methods: Type Parameter Syntax
What you'll learn: How to declare a method's own type parameter using the special <T> syntax before the return type.
The Core Idea
A generic method can have its own type parameter, completely independent of any class-level generics. To declare this, you place the type parameter in angle brackets <T> between the method's modifiers and its return type. This tells Java: "This method works with a type that will be specified when it's called."
The syntax looks like this:
public <T> T doSomething(T item) {
return item;
}
Notice the <T> comes before the return type T. The first <T> declares the type parameter; the second T uses it as the return type.
Why the Placement Matters
Think of it like introducing a variable before using it. The <T> declaration says "Hey, there's a type called T in this method," and then you can use T anywhere in the method signature or body.
This works even in non-generic classes:
public class RegularClass {
public <T> void printItem(T item) {
System.out.println(item);
}
}
Multiple Type Parameters
Just like with classes, methods can declare multiple type parameters:
public <K, V> void printPair(K key, V value) {
System.out.println(key + " : " + value);
}
The <K, V> before the return type declares both parameters for this method's use.
Key Takeaway: Generic methods declare their own type parameters using <T> syntax placed before the return type, making the method flexible regardless of whether the containing class is generic.