在JDK5以后java提供了泛型(Java Genertics),容许在定义类的时候使用类型做为参数。泛型普遍应用于各种集合中。本文对其以及其用法进行介绍。
public class Main { public static void main(String[] args) throws IOException { 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); } }
彷佛Object是String的父类,并无问题。可是,编译时候是不能经过的。报错以下:html
The method accept(ArrayList < Object > ) in the type Main is not applicable for the arguments (ArrayList < String > )
缘由是java类型擦除机制,在编译成class文件时候,编译器并未把Object和String类型信息编译进去。所以为了防止错误,编译器在编译时候发现他们不一致就会报错。java
List<?> 可接收任何类型。app
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 Object System.out.println(e); // in this method, because we don't know what type ? is, we can not add anything to al. } }
List< Object > - List can contain Object or it's subtype List< ? extends Number > - List can contain Number or its subtypes. List< ? super Number > - List can contain Number or its supertypes.
转自个人博客园( http://www.cnblogs.com/qins/p...