首页 > 代码库 > 数组与泛型容器区别

数组与泛型容器区别

一。基本

class Shape{    void draw(){        System.out.println(this+".draw()");    }}class Circle extends Shape{    @Override    public String toString() {        return "Circle";    }}class Rect extends Shape{    @Override    public String toString() {        return "Rect";    }}class Triangle extends Shape{    @Override    public String toString() {        return "Triangle";    }}class Square extends Rect{    @Override    public String toString() {        return "Square";    }}

 

二。示例

 1         Shape[] shapes = new Rect[10]; 2         shapes[0] = new Rect(); 3         //Shape类型的引用当然可以放入Circle。但数组在运行时能保留它存储的对象类型的倣,运行时是Rect,因此运行出错 4         //shapes[1] = new Circle(); // java.lang.ArrayStoreException 5  6          //数组与泛型容器的区别:数组有协变类型,而泛型容器没有内建协变类型 7         List<Shape> list = new ArrayList<Rect>();  //错误 8         List<? extends Shape> list = new ArrayList<Rect>(); 9         //放不进任何元素。10         //list.add(new Circle());11         //list.add(new Rect());12         13         List<Rect> list = new ArrayList<Rect>();14         //list.add(new Circle()); //泛型容器将运行时检查提前到编译期15         list.add(new Rect());16         list.add(new Square());17         for(Rect rect : list){18             rect.draw();19         }