Java记录 -44- Object数组陷阱
2015-10-25 23:29
357 查看
下面是一个很简单的程序,但存在了意想不到的陷阱:
但是注释的那行代码运行时会抛出如下异常:
有上面的实例证实了,不能将Object[]数组强制转换成Integer[]数组,不用怀疑了。
Integer对象继承了Object对象,但是Integer[]数组并没有继承Object[]数组,字面理解似乎不通了。
深层次一点理解,Object[]数组不单单能存放Integer对象,还可以存放比如字符串等等对象。
如果一个Object[]数组即存放了Integer对象,也存放字符串对象,还存放了Boolean对象;那么在讲Object[]数组强制转换为Integer[]数组时就会有问题,时无法将字符串和Boolean对象转换为Integer对象的。
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对象的。
相关文章推荐
- Objective-C 获取当前执行函数的名称
- Effective Objective-C 2.0 第8条:理解“对象等同性”概念
- Objective-C description的用法
- Objective-C 成员变量的访问修饰即成员变量可见性解析
- Foundation 之 NSDictionary和NSMutableDictionary
- 使用Buildozer部署时,出现AttributeError: 'NoneType' object has no attribute 'group'错误的解决
- Objective-C代码块Block详解
- Foundation 之 NSArray和NSMutableArray
- error C2248: “CObject::operator =”: 不可访问 private 员(于“CObject”类声明)
- Object C学习笔记2-NSLog 格式化输出数据
- Object方法和异常总结(4)
- Python标准库:内置函数hasattr(object, name)
- js引用类型之Object类型
- Exception starting filter struts2 java.lang.NoClassDefFoundError: org/objectweb/asm/ClassVisitor
- objective-c开发编码规范
- 学习ECMAScript5规范中Object新增的API
- javascript基本语法3 引用类型----Object
- QMetaObject::connectSlotsByName 总结
- Objective-C新特性
- 运行错误:error while loading shared libraries: xxx.so.0:cannot open shared object file: No such file or