Interview question
How do you write a generic method in Java? Java में generic method कैसे लिखें?
Answer
A generic method declares its own type parameter(s), independent of the class it's in, using angle brackets right before the return type.
public class Utility {
// Generic method - <T> before the return type declares the type parameter
public static <T> void printArray(T[] array) {
for (T item : array) {
System.out.println(item);
}
}
// Generic method with a return type using the type parameter
public static <T> T getFirst(List<T> list) {
return list.isEmpty() ? null : list.get(0);
}
// Multiple type parameters
public static <K, V> Map<V, K> invertMap(Map<K, V> original) {
Map<V, K> inverted = new HashMap<>();
for (Map.Entry<K, V> entry : original.entrySet()) {
inverted.put(entry.getValue(), entry.getKey());
}
return inverted;
}
// Bounded generic method
public static <T extends Comparable<T>> T findMax(List<T> list) {
T max = list.get(0);
for (T item : list) {
if (item.compareTo(max) > 0) max = item;
}
return max;
}
}
// Usage - type is usually INFERRED, no need to specify explicitly
Integer[] numbers = {1, 2, 3};
Utility.printArray(numbers); // T inferred as Integer
String first = Utility.getFirst(List.of('a', 'b', 'c')); // T inferred as String
// Explicit type witness (rarely needed)
Utility.<String>printArray(new String[]{'x', 'y'});public class Utility {
// Generic method - return type से पहले <T>
public static <T> void printArray(T[] array) {
for (T item : array) {
System.out.println(item);
}
}
public static <T> T getFirst(List<T> list) {
return list.isEmpty() ? null : list.get(0);
}
// Multiple type parameters
public static <K, V> Map<V, K> invertMap(Map<K, V> original) {
Map<V, K> inverted = new HashMap<>();
for (Map.Entry<K, V> entry : original.entrySet()) {
inverted.put(entry.getValue(), entry.getKey());
}
return inverted;
}
public static <T extends Comparable<T>> T findMax(List<T> list) {
T max = list.get(0);
for (T item : list) {
if (item.compareTo(max) > 0) max = item;
}
return max;
}
}
Integer[] numbers = {1, 2, 3};
Utility.printArray(numbers); // T = Integer inferred
String first = Utility.getFirst(List.of('a', 'b', 'c'));
Utility.<String>printArray(new String[]{'x', 'y'});Was this answer clear?