Java记录 -44- Object数组陷阱

下面是一个很简单的程序,但存在了意想不到的陷阱:

    public static void main(String[] args) {        ArrayList list = new ArrayList();        list.add(new Integer(1));        list.add(new Integer(2));        //      Integer[] ins = (Integer[])list.toArray();               Object[] ins = list.toArray();        for(int i=0;i<ins.length;i++){            System.out.println(ins[i]);        }    }

上面的程序可以执行,没有问题。

但是注释的那行代码运行时会抛出如下异常:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;            at my.arraylist.ArrayListTest.main(ArrayListTest.java:16)
Integer[] ins = (Integer[])list.toArray();

list.toArray()方法返回的是Object[]数组,Object[]数组强制转换为Integer[]数组,字面理解没有问题,编译时也没问题,但运行时会抛出异常,这是为什么呢?

  1. 有上面的实例证实了,不能将Object[]数组强制转换成Integer[]数组,不用怀疑了。

  2. Integer对象继承了Object对象,但是Integer[]数组并没有继承Object[]数组,字面理解似乎不通了。

  3. 深层次一点理解,Object[]数组不单单能存放Integer对象,还可以存放比如字符串等等对象。

  4. 如果一个Object[]数组即存放了Integer对象,也存放字符串对象,还存放了Boolean对象;那么在讲Object[]数组强制转换为Integer[]数组时就会有问题,时无法将字符串和Boolean对象转换为Integer对象的。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值