Class Level type Parameter
Type parameters are used as Type placeholders
public class List<T> { }
Here T is a type parameter.
Here List<T> is a container for T objects.
T can be any class Type.
List<T> can be List<String>, List<Integer> , List<User>
Similarly
Interface Map<K,V> holds two type parameters
It can be any class types.
class Forest<T>{
private T t;
public Forest(T t) {
this.t=t;
}
public T getT() {
return t;
}
}
public class TypeParamFlight {
public static void main(String[] bag) {
String str = new String("dove");
Forest<String> f1 = new Forest<String>(str);
String strVal = f1.getT();
System.out.println("strVal: "+strVal);
Forest<Integer> f2 = new Forest<Integer>(10);
Integer intVal = f2.getT();
System.out.println("intVal: "+intVal);
}
}
Output
strVal: dove
intVal: 10
public class List<T> { }
Here T is a type parameter.
Here List<T> is a container for T objects.
T can be any class Type.
List<T> can be List<String>, List<Integer> , List<User>
Similarly
Interface Map<K,V> holds two type parameters
It can be any class types.
class Forest<T>{
private T t;
public Forest(T t) {
this.t=t;
}
public T getT() {
return t;
}
}
public class TypeParamFlight {
public static void main(String[] bag) {
String str = new String("dove");
Forest<String> f1 = new Forest<String>(str);
String strVal = f1.getT();
System.out.println("strVal: "+strVal);
Forest<Integer> f2 = new Forest<Integer>(10);
Integer intVal = f2.getT();
System.out.println("intVal: "+intVal);
}
}
Output
strVal: dove
intVal: 10