Generic methods in Java are a powerful feature that allows developers to write flexible, reusable code that works with different data types. They provide type safety and eliminate the need for explicit type casting, making your code more robust and maintainable.
Generic methods are methods that introduce their own type parameters. This enables you to write a single method declaration that can be called with arguments of different types. The compiler ensures type safety, catching errors at compile-time rather than runtime.
The syntax for declaring a generic method is as follows:
public <T> returnType methodName(T parameter) {
// Method body
}
Here, T
is a type parameter that can be used within the method. You can use any valid identifier instead of T.
public class GenericMethodExample {
public static <E> void printArray(E[] array) {
for (E element : array) {
System.out.print(element + " ");
}
System.out.println();
}
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4, 5};
Double[] doubleArray = {1.1, 2.2, 3.3, 4.4, 5.5};
String[] stringArray = {"Hello", "World", "Generic", "Methods"};
System.out.println("Integer Array:");
printArray(intArray);
System.out.println("Double Array:");
printArray(doubleArray);
System.out.println("String Array:");
printArray(stringArray);
}
}
In this example, the printArray
method can work with arrays of any type, demonstrating the flexibility of generic methods.
public class MaxFinder {
public static <T extends Comparable<T>> T findMax(T a, T b, T c) {
T max = a;
if (b.compareTo(max) > 0) {
max = b;
}
if (c.compareTo(max) > 0) {
max = c;
}
return max;
}
public static void main(String[] args) {
System.out.println("Max of 3, 7, 2: " + findMax(3, 7, 2));
System.out.println("Max of 3.14, 2.78, 9.99: " + findMax(3.14, 2.78, 9.99));
System.out.println("Max of apple, pear, orange: " + findMax("apple", "pear", "orange"));
}
}
This example shows how to use generic methods with bounded type parameters, allowing comparison between objects of the same type.
T
for type, E
for element)To deepen your understanding of Java generics, explore these related topics:
By mastering generic methods, you'll be able to write more flexible and type-safe code in Java, improving your overall programming skills and the quality of your applications.