Generics · Topic 3 of 7
Generic methods
Definition​
A generic method has its own type parameter, written before the return type. Java works out the type from the arguments, so one method can serve many types safely.
Example code​
One method that works for any list or array
import java.util.List;
class Util {
static <T> T firstOf(List<T> list) {
return list.get(0);
}
static <T> void swap(T[] array, int i, int j) {
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
class Demo {
public static void main(String[] args) {
String firstName = Util.firstOf(List.of("Asha", "Ravi")); // T is String
int firstNumber = Util.firstOf(List.of(10, 20, 30)); // T is Integer
System.out.println(firstName + " " + firstNumber);
Integer[] numbers = {1, 2, 3};
Util.swap(numbers, 0, 2);
System.out.println(java.util.Arrays.toString(numbers));
}
}
// Output:
// Asha 10
// [3, 2, 1]
Finished this page? Track your progress (saved only in your browser).