Unbounded wildcards
The unbounded wildcard type是用通配符字母?来表示的,比如List<?>,我们把这个叫做一个未知类型的列表。
通常有两种情况特别适用使用unbounded wildcard type:
- 如果你写一个method,里面的实现是需要用到Object类的方法的
- 当你的代码用到generic class的方法,但是这个方法不依赖type parameter
例子:写一个方法打印出来列表中所有元素(并未告知是何种类型的列表)
public static void printList(List<?> list){
for(Object elem: list){
System.out.println(elem + " ");
}
}
List<Integer> l1 = Arrays.asList(1,2,3);
List<String> l2 = Arryas.asList("one", "two", "three");
printList(l1);
printList(l2);
这里你的方法就不能使用LIst<Object>,因为List<Integer>和List<String>都不是它的subtype,所以需要使用unbounded wildcard type,而且里面的实现println方法最终会调用Object的toString方法。
List<?> list = new ArrayList<String> ();
list.add("aString"); //does not compile - we don't know it is a List<String>
list.clear(); //this is fine, does not depend on the generic parameter type