How to Create Generic Method in Java: Syntax and Examples
To create a
generic method in Java, declare the type parameter before the return type in the method signature using angle brackets, like <T>. This allows the method to work with different data types while maintaining type safety.Syntax
A generic method declares its type parameter(s) before the return type using angle brackets. The syntax looks like this:
- <T>: Declares a generic type parameter named T.
- ReturnType: The type the method returns, which can be T or any other type.
- methodName: The method's name.
- Parameters: Method parameters can use the generic type T.
java
public <T> T genericMethod(T param) { return param; }
Example
This example shows a generic method that returns the same value it receives, demonstrating how to use a generic type parameter to handle different data types safely.
java
public class GenericMethodExample { // Generic method that returns the input parameter public static <T> T echo(T input) { return input; } public static void main(String[] args) { String text = echo("Hello World"); Integer number = echo(123); System.out.println(text); System.out.println(number); } }
Output
Hello World
123
Common Pitfalls
Common mistakes when creating generic methods include:
- Forgetting to declare the generic type parameter before the return type.
- Using raw types instead of generic types, which loses type safety.
- Trying to use primitive types directly as generic parameters (use wrapper classes like Integer instead).
java
/* Wrong: Missing generic type declaration before return type */ // public T wrongMethod(T param) { // return param; // } /* Right: Declare generic type parameter before return type */ public <T> T correctMethod(T param) { return param; }
Quick Reference
| Part | Description |
|---|---|
| Declares the generic type parameter(s) before the return type | |
| ReturnType | The type the method returns, can be generic (T) or specific |
| methodName | Name of the method |
| Parameters | Method parameters can use generic types |
| Usage | Allows method to work with any object type safely |
Key Takeaways
Declare generic type parameters before the return type using angle brackets.
Generic methods enable type-safe, reusable code for different data types.
Always use wrapper classes for primitives when using generics.
Avoid raw types to maintain compile-time type checking.
Generic methods can be static or instance methods.