Generic Methods in Java
Learn Java generic methods with examples for type inference, explicit type witnesses, bounded parameters, and safe generic varargs.
Learn Java generic methods with examples for type inference, explicit type witnesses, bounded parameters, and safe generic varargs.
Generic Methods in Java
A generic method is a method declared with its own type parameter, independent of the class it lives in. You can have generic methods in both generic and non-generic classes. The type parameter appears before the return type and is scoped to the method itself.
Introduction
Generic methods give an individual operation its own type parameter, whether or not the containing class is generic. For example, ArrayUtil.swap(T[] array, int i, int j) uses one method-level T for the array elements and temporary value. The compiler infers T from the arguments in most calls.
Collections.swap(List<?> list, int i, int j) is type-safe, but it is not a generic method: its signature uses a wildcard and declares no method type parameter. The array-based swap below is the generic-method example in this guide.
The distinction from a generic class is scope. A class type parameter is available to its members; a method type parameter exists only within that method. Generic methods suit utilities and factories that do not need to store type-specific state.
This guide covers generic method syntax, inference, bounds, and the safety rules for generic varargs.
When to Use Generic Methods
- Writing utility methods that operate on any type (swap, max, identity)
- Implementing static factory methods that preserve type information
- Creating conversion helpers (e.g.,
List<String>toSet<String>) - Building functional-style callbacks where the type is inferred
When NOT to Use Generic Methods
- The method performs identical operations for all types and no type-specific logic exists — a regular method is simpler
- You need primitive overloads for performance in hot paths (primitive specialization is more efficient than boxing)
- The added abstraction obscures intent and the method is rarely reused
- You are trying to force varargs with primitives into generics — use overloading instead
Code Example: Basic Generic Method
public class ArrayUtil {
// Generic static method — type parameter declared before return type
public static <T> void swap(T[] array, int i, int j) {
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static <T> int indexOf(T[] array, T target) {
for (int i = 0; i < array.length; i++) {
if (Objects.equals(array[i], target)) return i;
}
return -1;
}
}
// Usage — type inferred from arguments
String[] names = {"Alice", "Bob", "Charlie"};
ArrayUtil.swap(names, 0, 2); // type inferred as String
Code Example: Type Inference
import java.util.Collections;
import java.util.List;
public class InferenceDemo {
static <T> T identity(T value) {
return value;
}
public static void main(String[] args) {
String inferred = identity("Hello");
String explicit = InferenceDemo.<String>identity("Hello");
List<String> targetTyped = Collections.emptyList();
List<String> explicitEmpty = Collections.<String>emptyList();
System.out.println(inferred);
System.out.println(explicit);
System.out.println(targetTyped);
System.out.println(explicitEmpty);
}
}
Inference happens at compile time. The first call gets T from its argument; the second supplies a type witness explicitly. In the third line, the assignment target helps choose the type argument for emptyList(). The final line spells out the same type argument.
Run javac InferenceDemo.java && java InferenceDemo:
Hello
Hello
[]
[]
Code Example: Bounded Type Parameters
// T must be Comparable to its own type — enables .compareTo()
public static <T extends Comparable<T>> T max(T a, T b) {
return a.compareTo(b) >= 0 ? a : b;
}
// Works
Integer maxInt = max(10, 20); // Integer implements Comparable<Integer>
String maxStr = max("apple", "banana"); // String implements Comparable<String>
// Fails to compile — Double does not implement Comparable<Double>
// double bad = max(1.0, 2.0); // compile error
Code Example: Generic Varargs
import java.util.ArrayList;
import java.util.List;
public class SafeVarargsCopyDemo {
@SafeVarargs
static <T> List<T> copyOf(T... elements) {
List<T> copy = new ArrayList<>(elements.length);
for (T element : elements) {
copy.add(element);
}
return copy;
}
public static void main(String[] args) {
List<String> names = copyOf("Ada", "Grace");
System.out.println(names);
}
}
The program prints [Ada, Grace].
T... is non-reifiable. Without an annotation, the compiler can warn at the declaration and at calls that create a generic array. @SafeVarargs is a programmer assertion that the body does not use the array unsafely; here the method reads each element and copies it into a new list without returning or retaining the array.
The annotation is legal on variable-arity constructors and on variable-arity static, final, or private instance methods. Private instance methods became eligible in Java 9. It suppresses specific unchecked warnings; it does not change runtime behavior or make an unsafe method safe.
Mermaid Diagram: Generic Method Resolution
sequenceDiagram
participant Caller
participant Compiler
participant JVM
Caller->>Compiler: ArrayUtil.swap(names, 0, 2)
Note over Compiler: Infer T = String from String[] arg
Compiler->>Compiler: Emit swap(Object[], int, int) after erasure
Compiler->>JVM: Bytecode: swap(Object[], int, int)
Caller->>JVM: Passes the String[] reference to the erased Object[] parameter
Note over JVM: The array still has its String[] runtime component type
Failure Scenarios
1. Bounded Type Violation
When a type parameter is bounded with extends, the bound constrains which types qualify as valid arguments, but it does not change the fundamental operations available on the type. <T extends Number> tells the compiler that T is a Number or a subclass of Number, which means the erased type of T is Number. This makes Number-level methods available on variables of type T, but it does not make numeric operators like +, -, *, / work on T directly.
// A method with this body would not compile:
// static <T extends Number> T invalidSquare(T value) {
// return value * value;
// }
static <T extends Number> double square(T value) {
return value.doubleValue() * value.doubleValue();
}
The * operator in Java works only on primitive numeric types — int, long, float, double — and is not overloaded for objects. Even though Integer and Double represent numbers, the * operator does not work on them. The bound extends Number makes the erased type Number, which does have doubleValue() and intValue() methods, but those are method calls, not operators. The compiler rejects value * value because T is erased to Number, Number does not define a * operator, and the JVM bytecode for multiplication only operates on primitive values on the operand stack.
The fix uses the boxed type’s API — value.doubleValue() returns a primitive double, and primitives do support arithmetic operators. The return type changes from T to double because the operation no longer produces a value of type T; it produces a primitive that must be autoboxed on assignment. If you need the result as type T, you would need to know the specific subtype to call its constructor or factory method — which is not possible without an explicit Class<T> token. The practical choice is to return the primitive and let the caller handle the type conversion, which is what the standard library does in similar situations.
2. Creating an Array with a Runtime Type Token
// Generates compiler warning: "Possible heap pollution from parameterized vararg type"
// public static <T> T[] toArray(List<T> list) {
// return list.toArray(new T[list.size()]); // compile error on new T[...]
// }
// Safe approach using Class<T>
public static <T> T[] toArray(List<T> list, Class<T> clazz) {
@SuppressWarnings("unchecked")
T[] result = (T[]) Array.newInstance(clazz, list.size());
return result;
}
Trade-Off Table
| Aspect | Generic Method | Overloaded Methods | Object + Cast |
|---|---|---|---|
| Type safety | Compile-time enforced | Compiler chooses overload | Runtime exception risk |
| Code size | Single method | N copies (one per type) | One method |
| Readability | Slightly abstract | Explicit and clear | Obfuscated at call sites |
| Performance | Identical (erasure) | May allow primitive specialization | Identical |
| Binary compat | Preserved | Breaking if signatures change | Preserved |
Observability Checklist
- Verify type inference works at all call sites — compiler errors catch mismatches, but complex inference chains can silently pick the wrong type
- Add
@SafeVarargsonly to an eligible varargs constructor or method after checking that its body does not expose or corrupt the varargs array - Log generic method signatures in documentation (Javadoc
@param <T>) — IDEs show type parameter info - Check for unchecked cast warnings in static analysis output
- Ensure reflection-based calls to generic methods specify correct type tokens
Security Notes
-
Heap pollution: A generic varargs array can be corrupted if code stores values of an incompatible parameterized type through an alias or exposes the array to unsafe code.
@SafeVarargsis an assertion about the body, not a runtime check. Avoid retaining or exposing the array; validate untrusted values at the application boundary where their expected type is known. -
Type tokens: When using
Class<T>to reify generics at runtime (e.g., forArray.newInstance), ensure theClassobject comes from a trusted source — a malicious caller could pass a dangerous class. -
Reflection exposure: Reflection can expose generic signature metadata through methods such as
Method.getGenericParameterTypes(). That metadata describes declarations; it does not validate type arguments or values at runtime.
Pitfalls
-
Target type and inference: Inference uses invocation arguments and, where applicable, the expected result type. A generic method whose type parameter appears only in its return type may need a target type or an explicit type witness.
-
Primitive arrays:
swap(int[] arr, 0, 1)does not work withswap(T[] array, ...)— you need separate overloads for primitives. -
Conflicting type bounds: If one branch of an
if-elsereturns different bounded types, the compiler may reject the merge.
Quick Recap
- Generic method syntax:
<T> T methodName(T arg)— type param before return type - Type inference uses invocation arguments and target context;
Owner.<String>method(...)supplies an explicit type witness - Bounded type parameters (
<T extends Comparable<T>>) enable calling methods onT @SafeVarargsis an assertion for eligible declarations; it suppresses specific warnings but does not make an unsafe body safe- Erasure changes runtime method descriptors; generic signature metadata can still be available to reflection
Key Takeaways
Generic methods stand apart from generic classes because their type parameter is scoped to the method. In the ArrayUtil.swap(T[] array, int i, int j) example, the method declares T; Collections.swap(List<?> list, int i, int j) instead uses a wildcard and declares no method type parameter.
The compiler infers method type arguments from invocation arguments and, where applicable, the target context. ArrayUtil.swap(names, 0, 2) gets T = String from the array. A type witness such as InferenceDemo.<String>identity("Hello") spells out the choice.
Bounded type parameters (<T extends Comparable<T>>) let the compiler check calls such as .compareTo(). Without the bound, the type parameter has only its implicit Object bound, so those calls are unavailable.
@SafeVarargs is legal only on variable-arity constructors and static, final, or private methods. It asserts that the body handles its varargs array safely and suppresses specific unchecked warnings. It does not prevent heap pollution; the example above copies values and does not expose the array.
For how bounds interact with method signatures in class hierarchies, see Type Bounds in Java Generics. Type Erasure in Java Generics explains how compile-time checks relate to runtime method descriptors.
Interview Questions
Model Answer:
public static <T> List<T> merge(List<T> a, List<T> b) {
List<T> result = new ArrayList<>(a);
result.addAll(b);
return result;
}
The type parameter `T` is inferred from both list arguments, and both must resolve to the same type — `merge(List<String>, List<Integer>)` would be a compile error. The method returns `List
Further Reading
- Generic Classes — defining classes with type parameters
- Generic Methods — writing flexible methods with type parameters
- Wildcards — unbounded and bounded wildcard type arguments
- Type Erasure — how generics are erased at compile time
- Type Bounds — upper and lower bounds on type parameters
- Bridge Methods — compiler-generated methods from type erasure
- Oracle: Generic Methods — official documentation on generic method declarations
- JLS SE 27 Chapter 15 — method invocation and type inference rules
- JLS SE 27 §9.6.4.7:
@SafeVarargs— annotation eligibility and compile-time rules - Java SE 27
SafeVarargsAPI — annotation contract and restrictions - Java SE 27
CollectionsAPI — includes the wildcard signature forCollections.swap - Oracle Tutorial: Type Inference — argument and target type examples
Conclusion
Generic methods give one operation a type parameter without making the containing class generic. The parameter belongs to that method, and the compiler infers it from invocation arguments and, where available, the result’s target type. A type witness makes the choice explicit when needed.
Erasure prevents new T(), T.class, and instanceof T; bounds let the compiler check calls such as compareTo(). @SafeVarargs is an assertion for eligible varargs declarations, not a runtime safety check. See Generic Classes in Java for type parameters on reusable classes and data holders.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.