package simplejava;import java.util.ArrayList;public class Q29 {public static void main(String[] args) {ArrayList<String> al = new ArrayList<String>();al.add("a");al.add("b");accept(al);}public static void accept(ArrayList<Object> al) {for (Object o : al)System.out.println(o);}}以上代码看起来是没问题的,因为String是Object的子类。然而,这并不会工作,编译不会通过,并提示如下错误: The method accept(ArrayList<Object>) in the type Q29 is not applicable for the arguments (ArrayList<String>)
List<? >表示List能包含任何类型的元素public static void main(String args[]) {ArrayList<Object> al = new ArrayList<Object>();al.add("abc");test(al);}public static void test(ArrayList<?> al) {for (Object e : al) {// no matter what type, it will be ObjectSystem.out.println(e);// in this method, because we don’t know what type ? is, we can not// add anything to al.}}永远记住,泛型是一个编译时的概念。在这个例子中,由于我们不知道?,我们不能添加任何元素到al集合。如果想要添加的话,可以使用通配符。List< Object > - List can contain Object or it’s subtypeList< ? extends Number > - List can contain Number or its subtypes.List< ? super Number > - List can contain Number or its supertypes.