10.5. Introduction - Generic Methods¶
Just like classes, we can also have generic methods! As you saw in the shipping container example, to make a class generic, we declare the generic type parameter as part of the class declaration. Similarly, to make a method generic, we declare the type parameter in the method declaration (in the signature of the method).
Note
The scope of a generic type parameter(s) works the same way as other variables/parameters you have seen. If the type parameter(s) is declared in a method signature, its scope is only within that method. Type parameter(s) declared in the class declaration are visible within the entire class.
Here is an example that allows us to print the items of an array of any type:
public class Utility {
public static <T> void printArray(T[] array) {
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
} // for
} // printArray
} // Utility
Its worth emphasizing that this method works for any array of any data type meaning that you would only need this one method to print arrays of strings and arrays of integers, for example.
The following examples will compile and run as expected!
String[] strings = new String[] {"Hello", "CSCI", "1302", "Students!"};
Integer[] integers = new Integer[] {17, 42 ,37, 81, 92};
Double[] doubles = new Double[] {4.2, 3.874};
Utility.printArray(strings);
Utility.printArray(integers);
Utility.printArray(doubles);
All without having to create another method!