Useage of Generic in Java
the usage of generic in class
//
public class A <T>{ //without specify a parent class or implemented interface as the super bound for generic type
T n;
public void printstr(){
System.out.println(n);
}
A(T a){
this.n=a;
System.out.println("A构建成功 "+a.getClass().getSimpleName());
}
public static void main(String[] args) {
A<String> a=new A("hellow world");
}
}
//specify Class A or implemented interface as the super bound for gerceric type T
public class B <T extends A>{ //”T extends B & C“ you can use & operator to specify multiple interface when bounding a generic type parameter. If there is a parent,ther parent class must put the first.
T a;
B(T a){
this.a = a;
}
public void A_method(){
a.printstr();
}
public static void main(String[] args) {
B b=new B(new A("testb"));
b.A_method();
}
}
the usage of generic in method
public class Main {
public static <T> void Obj_Print(T a){ //in gerneric method,the type declaration must be placed before the return type
System.out.println(a.getClass());
}
public static void main(String[] args) {
Obj_Print("Hello World");
}
}
now ,suppose i need create a function,which’s method is printing the elements’type of list,weather the list contains any type;
maybe you think of the fowlling methods,however it's fault
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("A");
listPrint(list);
}
public static <T> void listPrint(List<Objects> list){
System.out.println(list.getClass());
}
the reason of the erro?
Although Object is super class of String,but List<Objects> isn’t the super class of List<String>
the proper way: use wild card
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("A");
listPrint(list);
}
public static <T> void listPrint(List<?> list){
System.out.println(list.getClass());
}
finally: the opposite usage of “extends” is “super”; specify the subclass or implemented interface as low bound for generic