泛型[摘抄]
上一篇 / 下一篇 2008-01-10 17:57:13 / 个人分类:做着
1泛型编译后实际上会产生不同的类型声明
publicinterfaceList<E>{ voidadd(Ex); Iterator<E>iterator(); } publicinterfaceIterator<E>{ Enext(); booleanhasNext(); }
|
基本的调用
List<Integer>myIntList=newLinkedList<Integer>(); myIntList.add(newInteger(0)); Integerx=myIntList.iterator().next();
|
Note 1:每个泛型声明仅编译一次,并且为每个不同类型产生一个单独的文件。就像旧的类一样。比如,可能会有List<Integer>类和List<Boolean>类被产生。
原文:A generic type declaration is compiled once and for all, and turned into a single class file, just like an ordinary class or interface declaration.
编译后,相当于产生了下面的类
publicinterfaceIntegerList{ voidadd(Integerx); Iterator<Integer>iterator(); }
|
2 List<String>不是List<Object>的子类型
以下语句将无法通过编译,出现错误在第2行,因为lo不是ls的父类型。
List<String>ls=newArrayList<String>(); List<Object>lo=ls;
lo.add(newObject(); Strings=ls.get(0);
|
Note 2:一般来说,如果Foo是Bar的子类型,G是泛型类型,那么G<Foo>不是G<Bar>的子类型。书上说这是泛型学习的最大难点。
原文:In general, ifFoois a subtype (subclass or subinterface) ofBar, andGis som generic type declaration, it isnotthe case thatG<Foo>is a subtype ofG<Bar>.
3泛型的父类型是<?>,通配符类型。
一个用到Collection的泛型方法如下,其中for循环用了新式的方法:
voidprintCollection(Collection<?>c){ for(Objecte:c) System.out.println(e); }
|
其中,Collection<?>表示其可以是任何类型。如Collection<Integer>,Collection<String>,Collection<?>是他们的父类型。
Note 3:Collection<?>是所有种类的子类。而不是Collection<Object>。这叫做“wildcard type”通配符类型。
原文:What is the supertype of all kinds of collections? It’s written Collection<?> (pronounced “collection of unknown”), that is, a collection whose element type matches anything. It’s called a wildcard type for obvious reason.
4 Bounded wildcards.有限制的通配符类型
很不幸,下面的方法调用无法成功。虽然List<Circle>中的每个对象都是Shape类型。
publicvoiddrawAll(List<Shape>shapes){ for(Shaps:shapes)s.deaw(); } drawAll(List<Circle>circles);
|
通过bounded wildcard可以解决:然而这样做会带来一点代价。即,它是只读的,你不能再向List中添加新元素。
publicvoiddrawAll(List<?extendsShape>shapes){ //下面的调用是错误的,只能读 shapes.add(0,newCircle()); }
|
Note 4:<? extends Class>是一种限制通配符类型,它可以接受所有<Class>以及Class的子类型。然而调用代价是,只读访问。
原文:We have replaced the type List<Shape> with List<? extends Shape>. Now drawAll() will accept lists of any subclass of Shape. It is an example of a bounded wildcard. It is now illegal to write into shapes in the body of the method.
发表于:2004.12.24 13:43
导入论坛 引用链接 收藏 分享给好友 推荐到圈子 管理 举报
TAG: