Java不能创建泛型数组

一,数组的协变性(covariant array type)及集合的非协变性

设有Circle类和Square类继承自Shape类。

关于数组的协变性,看代码:

public static double totalArea(Shape[] arr){
        double total = 0;
        for (Shape shape : arr) {
            if(shape != null)
                total += shape.area();
        }
        return total;
}

如果给 totalArray(Shape[] arr) 传递一个Circle[] 类型的数组,这是可以的,编译通过,也能正常运行。也就是说:Circle[] IS-A Shape[]

关于集合的协变性,看代码:

public static double totalArea(Collection<Shape> arr){
        double total = 0;
        for (Shape shape : arr) {
            if(shape != null)
                total += shape.area();
        }
        return total;
 }

如果给totalArea(Collection< Shape> arr)传递一个 Collection< Circle>类型的集合,这是不可以的。编译器就会报如下的错误:

The method totalArea(Collection< Shape>) in the type Demo is not applicable for the arguments (Collection< Circle>)
也就是说:Collection< Circle> IS-NOT-A Collection< Shape>

二,如果解决集合的非协变性带来的不灵活?

出现了泛型!

public static double totalArea(Collection<? extends Shape> arr){
        double total = 0;
        for (Shape shape : arr) {
            if(shape != null)
                total += shape.area();
        }
        return total;
}

这样,就可以给totalArea(Collection<? extends Shape> arr)传递Collection< Circle>、Collection< Square>、Collection< Shape>类型的参数了。

三,泛型的类型擦除及类型擦除带来的ClassCastException异常
JAVA的泛型只存在于编译层,到了运行时,是看不到泛型的。

先假设Java可以创建泛型数组,由于java泛型的类型擦除和数组的协变。下面的代码将会编译通过。

List<String>[] stringLists=new List<String>[1];
List<Integer> intList = Arrays.asList(40);
Object[] objects = stringLists;
Objects[0]=intList;
String s=stringLists[0].get(0);

由于泛型的类型擦除,List< Integer>,List< String>与List在运行期并没有区别,所以List< String>放入List< Integer>并不会产生ArrayStoreException异常。但是String s=stringLists[0].get(0);将会抛出ClassCastException异常。如果允许创建泛型数组,就绕过了泛型的编译时的类型检查,将List< Integer>放入List< String>[],并在实际存的是Integer的对象转为String时抛出异常。

如果泛型没有限制类型。比如List s=new ArrayList[5];或者List<?>[] s=new ArrayList[5];还是可以使用的,因为没有了编译时的类型检查,需要开发者自己保证类型转换安全。

猜你喜欢

转载自blog.csdn.net/qq_32534441/article/details/83833868