您的位置:首页 > 移动开发 > Objective-C

Java记录 -44- Object数组陷阱

2015-10-25 23:29 357 查看
下面是一个很简单的程序,但存在了意想不到的陷阱:

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[]数组,字面理解没有问题,编译时也没问题,但运行时会抛出异常,这是为什么呢?
有上面的实例证实了,不能将Object[]数组强制转换成Integer[]数组,不用怀疑了。

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

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

如果一个Object[]数组即存放了Integer对象,也存放字符串对象,还存放了Boolean对象;那么在讲Object[]数组强制转换为Integer[]数组时就会有问题,时无法将字符串和Boolean对象转换为Integer对象的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: