Generic Static Methods: Utility Method Patterns
What You'll Learn
You'll learn why and how to write generic static methods in utility classes where making the entire class generic would be inappropriate or awkward.
The Core Idea
Many utility classes (like Collections, Arrays, or custom helpers) provide static methods that operate on different types—but the class itself doesn't need to be generic. For these scenarios, generic static methods are the perfect tool.
A static generic method declares its own type parameter(s) independent of any class-level generics. This means you can write a single utility method that works with any type, without forcing users to parameterize the entire class.
When to Use This Pattern
- Utility classes that only contain static methods (like
MathorCollections) - Factory methods that create and return generic objects
- Conversion or transformation operations that work across types
- Any static method that benefits from type safety without class-level context
Syntax Reminder
public static <T> T identity(T input) {
return input;
}
The <T> before the return type declares the method's type parameter—this is separate from class-level generics.
Real-World Example Pattern
public class Utilities {
// Static generic method - no class-level <T> needed
public static <T> T firstElement(T[] array) {
return array.length > 0 ? array[0] : null;
}
public static <E> void swap(E[] array, int i, int j) {
E temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
// Usage with type inference
String first = Utilities.firstElement(new String[]{"a", "b"});
Utilities.swap(new Integer[]{1, 2, 3}, 0, 2);
Notice Utilities itself isn't generic—only its methods are.
Key Takeaway:
Generic static methods let you write type-safe utility methods without making the entire class generic—perfect for helper and factory patterns where each method needs its own type flexibility.