博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Generics

Posted on 2011-09-20 09:42  douyamumu  阅读(202)  评论(0)    收藏  举报
In general, if Foo is a subtype (subclass or subinterface) of Bar, and G is some generic type declaration, it is not the case that G<Foo> is a subtype of G<Bar>. This is probably the hardest thing you need to learn about generics, because it goes against our deeply held intuitions.
e.g.
List<String> ls = new ArrayList<String>();
List<Object> lo = ls; //error

 

注:假如定义Animal为一个类,Cat,Dog等都继承Animal,现在有一个ArrayList<Animal>的对象c,那么往c里放入任何Animal的对象或者继承Animal的类的对象都是合法的;但是要注意的是(正如前边所说),ArrayList<Dog>并不是ArrayList<Animal> 的子类,它们是完全不相关的两个类,将ArrayList<Dog>对象的引用赋值给ArrayList<Animal>对象的引用会造成编译错误(如上例子,又比如果一个method需要ArrayList<Animal>类型的参数,但是却传递进去一个ArrayList<Dog>类型的实参,这就会引起编译错误。