Generic Methods
Generic methods are used to implement generic algorithms.
Example:
// non type-safe
void printArray(Object[] arr) {
for(Object ele : arr)
System.out.println(ele);
System.out.println("Number of elements printed: " + arr.length);
}
// type-safe
<T> void printArray(T[] arr) {
for(T ele : arr)
System.out.println(ele);
System.out.println("Number of elements printed: " + arr.length);
}
String[] arr1 = { "John", "Dagny", "Alex" };
printArray(arr1); // printArray<String> -- String type is inferred
Integer[] arr2 = { 10, 20, 30 };
printArray(arr2); // printArray<Integer> -- Integer type is inferred
Cannot instantiate generic types with primitive Types. Only reference types are allowed.
ArrayList<Integer> list = new ArrayList<Integer>(); // okay Array
List<int> list = new ArrayList<int>(); // compiler error
Cannot create instances of Type parameters.
Integer i = new Integer(11); // okay
T obj = new T(); // error
Cannot declare static fields with generic type parameters.
class Box<T> {
private T obj; // okay
private static T object; // compiler error
// ...
}
Cannot use casts or instanceof with generic Type params.
if(obj instanceof T) { // compiler error
newobj = (T)obj; // compiler error
}
Cannot create arrays of generic parameterized Types
T[] arr = new T[5]; // compiler error
Cannot create, catch, or throw Objects of Parameterized Types
throw new T(); // compiler error
try {
// ...
} catch(T ex) { // compiler error
// ...
}
Cannot overload a method just by changing generic type. Because after erasing/removing the type param, if params of two methods are same, then it is not allowed.
public void printBox(Box<Integer> b) {
// ...
}
public void printBox(Box<String> b) { // compiler error
// ...
}
Box<Integer>
and Box<Double>
both are internally (JVM level) treated as Box
objects. The field "T obj" in Box class, is treated as "Object obj".