Generic Methods in Non-Generic Classes
What you'll learn: How to create generic methods inside ordinary, non-generic classes.
You Don't Need a Generic Class to Use Generics
Here's a surprising fact: a class doesn't need type parameters to contain generic methods. You can write static or instance methods that have their own type parameters, completely independent of the class itself.
Think of it like this: a non-generic toolbox (the class) can still contain tools (methods) that work with any type of material you hand them. The toolbox itself isn't parameterized, but individual tools are flexible.
Syntax Reminder
Generic methods declare their type parameters before the return type:
public class Utilities {
// Static generic method
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
// Instance generic method
public <E> E getFirst(E[] items) {
if (items.length > 0) {
return items[0];
}
return null;
}
}
Notice: Utilities itself has no type parameters, but both methods do.
Using Them
String[] words = {"Hello", "World"};
Integer[] numbers = {1, 2, 3};
Utilities.printArray(words); // Type inference: T is String
Utilities.printArray(numbers); // Type inference: T is Integer
Utilities util = new Utilities();
String first = util.getFirst(words); // E is String
Why This Matters
This pattern is extremely common in utility classes (like Collections or Arrays in the standard library). You get type safety and reusability without making the entire class generic.
Key Takeaway: Generic methods can exist in non-generic classes—the method's type parameters are independent of the class declaration, making them perfect for utility operations that work with any type.