T 代表一种类型
加在类上==============》class SuperClass<A>{}
加在方法上============》public <T>void fromArrayToCollection(T[] a, Collection<T> c){}
(注)方法上的<T>代表括号里面要用到泛型参数,若类中传了泛型,此处可以不传,调用类型上面的泛型参数,前提是方法中使用的泛型与类中传来的泛型一致。
class People<T>{
public void show(T a) {
}
}
?是通配符,泛指所有类型
一般用于定义一个引用变量,这么做的好处是,定义一个sup的引用变量,就可以指向多个对象。
SuperClass<?> sup = new SuperClass<String>("lisi");
sup = new SuperClass<People>(new People());
sup = new SuperClass<Animal>(new Animal());
T和?运用的地方有点不同,?是定义在引用变量上,T是类上或方法上
如果有泛型方法和非泛型方法,都满足条件,会执行非泛型方法
public void show(String s){
System.out.println("1");
}
@Override
public void show(T a) {
System.out.println("2");
}
类型参数“<T>” 声明泛型类或泛型方法。
无界通配符“<?>”使用泛型类或泛型方法
写成T就是将类型固定,而?则不固定