简体   繁体   English

Java DataStructures 问题装箱/拆箱

[英]Java DataStructures question boxing/unboxing

I am studying for a data structures exam tommorrow and need to know what lines in the following code are correct and which aren't and why我正在学习明天的数据结构考试,需要知道以下代码中的哪些行是正确的,哪些是不正确的以及为什么

Object  obj = new Integer(42);
Integer iObj = 43;
iObj = obj;
HelloWorld.java:19: error: incompatible types: Object cannot be converted to Integer
        iObj = obj;
               ^
1 error

The above fails because the compile time type of iObj and obj are not matching.上述失败是因为 iObj 和 obj 的编译时类型不匹配。 This is a signature of strongly typed languages.这是强类型语言的签名。 Similar code in Javascript would work fine. Javascript 中的类似代码可以正常工作。

Answer to your question is here under:您的问题的答案如下:

 Object  obj = new Integer(42); //auto boxing  // true
 Integer iObj = 43; //direct intialization   //true
 iObj = obj  // false
 iObj = (Integer) obj; // manual boxing 

iObj = obj is false because obj is a reference to the Object and iObj is of Interger . iObj = obj is false ,因为obj是将一个参考ObjectiObjInterger Object is the parent of all and so Integer type iObj is child of obj and hence false. Object是 all 的父类,因此 Integer 类型iObjobj子类,因此为 false。

 In short, child can be auto- boxed to parent but the vice-versa is not possible

所有这些行都是正确的首先你创建对象和 tgen 你创建整数并将值分配给该整数对象这行代码是完全正确的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM