标签:object数组陷阱 java记录
下面是一个很简单的程序,但存在了意想不到的陷阱:
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对象的。
标签:object数组陷阱 java记录
原文地址:http://zlfwmm.blog.51cto.com/5892198/1706160