简体   繁体   English

使用对象在java中自动装箱

[英]Autoboxing Unboxing in java using Object

Using Object type object for autoboxing is working but it is not working for unboxing.使用Object类型对象进行自动装箱工作,但它不适用于拆箱。 What is the reason behind it.背后的原因是什么。 I mean about not working of unboxing feature for Object type object.我的意思是不使用对象类型对象的拆箱功能。 Is any special reason to implement this behaviour.实施此行为是否有任何特殊原因。 Because its support autoboxing but not support unboxing.When it comes to Integer class it support both autoboxing and unboxing.因为它支持自动装箱但不支持拆箱。当涉及到Integer类时,它同时支持自动装箱和拆箱。 And c# also supports autoboxing and unboxing for Object type object.并且 c# 还支持 Object 类型对象的自动装箱和拆箱。

class Demo{
    public static void main(String args[]){

        int x=100;
        Object iob1=new Object();

        Object iob2=x;  //Auto Boxing

        System.out.println(iob2.toString());

        int y = x + iob1;   //Unboxing is not working
        int z = x + new Integer(10); // Unboxing is working
        System.out.println(y);
    }
}

Unboxing is working quite fine.拆箱工作非常好。 BUT only for Double , Integer , etc.. iob1 is of type Object , so it can't work.仅适用于DoubleIntegeriob1Object类型,因此它无法工作。 The jls lists types that can be un-/boxed here . jls 列出了可以在此处取消/装箱的类型。

int y = x + iob1;

The + operator cannot have an int and an Object (How do you expect to add a number to an object?). +运算符不能有intObject (您希望如何向对象添加数字?)。 See this section from the Java Language Specification :请参阅Java 语言规范中的这一部分

If the type of either operand of a + operator is String , then the operation is string concatenation.如果+运算符的任一操作数的类型为String ,则该操作为字符串连接。

Otherwise, the type of each of the operands of the + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.否则, +运算符的每个操作数的类型必须是可转换(第 5.1.8 节)为原始数字类型的类型,否则会发生编译时错误。

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

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