A Generic Method is a method that can operate on different types of data. Instead of hardcoding a data type, it uses a type parameter (like <T>
) to define the type when the method is called.
Generic methods allow for:
- Code reuse
- Compile-time type safety
- No need for casting
Syntax
public <T> void methodName(T parameter) {
// Method body
}
<T> is a type parameter declaration placed before the return type.
You can use any valid identifier (T, E, K, V are conventional).
Code language: PHP (php)
Program-1: Simple Generic Method
public class Utility { // Generic method to print any type public static <T> void printItem(T item) { System.out.println("Item: " + item); } public static void main(String[] args) { printItem("LotusJavaPrince"); printItem(100); printItem(55.5); } } /* Item: LotusJavaPrince Item: 100 Item: 55.5 */
Example 2: Generic Method with Arrays
public class ArrayPrinter { // Generic method to print elements of any array public static <T> void printArray(T[] array) { for (T element : array) { System.out.print(element + " "); } System.out.println(); } public static void main(String[] args) { Integer[] intArray = {1, 2, 3}; String[] strArray = {"Lotus", "Java", "Prince"}; printArray(intArray); printArray(strArray); } } /* 1 2 3 Lotus Java Prince */
Example 3: Bounded Type Parameters in Generic Methods
public class Calculator { // Generic method to find the maximum of two numbers public static <T extends Number> double add(T a, T b) { return a.doubleValue() + b.doubleValue(); } public static void main(String[] args) { System.out.println(add(10, 20)); // int System.out.println(add(5.5, 4.5)); // double } } /* 30.0 10.0 */
Example 4: Generic Method with Multiple Type Parameters
public class PairPrinter { // Generic method with two type parameters public static <K, V> void printPair(K key, V value) { System.out.println("Key: " + key + ", Value: " + value); } public static void main(String[] args) { printPair("EmployeeID", 1001); printPair(200, "Mahesh"); } } /* Key: EmployeeID, Value: 1001 Key: 200, Value: Mahesh */
Example 5: Generic Method with Custom Objects (e.g., Employee)
public class Employee { String name; int id; public Employee(String name, int id) { this.name = name; this.id = id; } @Override public String toString() { return "Employee[ID=" + id + ", Name=" + name + "]"; } } public class Display { // Generic method public static <T> void showDetails(T obj) { System.out.println("Details: " + obj); } public static void main(String[] args) { Employee emp = new Employee("LotusJavaPrince", 101); showDetails(emp); showDetails("Generic Example"); } } /* Details: Employee[ID=101, Name=LotusJavaPrince] Details: Generic Example */