通配符也是类型实参(type argument)
?
表示任意类型中的一种
无界通配符是其他所有泛型类型的SuperType
所以可以被其他类型赋值,但是反过来不行
ArrayList<?> list1 = new ArrayList<Long>(); //可以赋值,子类类型赋值给父类类型
ArrayList<Long> list = list1; // error 父类类型不可以赋值给子类类型
1.通配符和raw type
的区别
编译器将发送错误信息给通配符,而发送警告信息给raw type.
2.通配符类型变量的操作
package com;
class Plate<T> {
private T t;
public void put(T t) { this.t = t;}
public T get() { return t; }
}
public class App2 {
public static void main(String[] args) {
Plate<?> plate = new Plate<String>();
// plate.put("apple"); //error 因为不知道什么类型,所以不能添加
Object o = plate.get(); // 因为不知道什么类型,而无论什么类型都是Object的子类,所以可以用Object接收
}
}
参考:
http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html#Wildcards
http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ302