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[]

数组的协变性(covariant)是指如果类Base是类Sub的基类,那么Base[]就是Sub[]的基类。而泛型是不可变的(invariant),List不会是List的基类,更不会是它的子类。

数组的协变性可能会导致一些错误,比如下面的代码:

public static void main(String[] args) {   
    Object[] array = new String[10];   
    array[0] = 10;   
}    

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

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];还是可以使用的,因为没有了编译时的类型检查,需要开发者自己保证类型转换安全。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值