Type Parameters
- Type parameter naming conventions is single upper case letters.
- Type parameter are specified between <> angle brackets. i.e <T>
- This pair of angle brackets <>, is called the diamond.
- Type parameters can be provided at the class level or metod level.
- Type parameters provide you a way to use the same code for different types inputs.
- The passed data type is checked at compile time. Which checks the problems at compile time.
- Type parameters eliminate explicit type casting.
- Type parameter and Type argument both are different
- Test<T> here T is type parameter
- Test<String> here String is type argument.
- There can be multiple type parameters : class Test<K,V>{}
T - Type
V - Value
K - Key
E - Element (It is majorly used by Java Collections Framework)
N - Number
Class level type parameter
class Test<T>{
public void print(T t){};
public void printList(List<? extends T> list){}
}
Method level type parameter
class Test{
public <T> void print(T t);
public <? extends T> void printList(List<T> list){}
}
Method level type parameter scope is limited to method only.