【问题标题】:Java: Difference between these two wrapper class statements [duplicate]Java:这两个包装类语句之间的区别[重复]
【发布时间】:2023-04-05 20:55:01
【问题描述】:

我是编程新手。告诉我两者的区别 Integer x= 59;Integer x= new Integer (59); 他们基本上都做同样的事情,我得到了任何一种方式的输出。

public class WrapperClass
{
    public static void main(String args[]) 
    {
        Integer x= 59; // 
        byte y= x.byteValue();
        System.out.println(y);
    }
}

public class WrapperClass
{
    public static void main(String args[]) 
    {
        Integer x = new Integer (10);
        byte y= x.byteValue();
        System.out.println(y);
    }
}

【问题讨论】:

标签: java wrapper


【解决方案1】:

差别不大。自动装箱(Integer x = 59;)将调用Integer.valueOf( 59 );,而另一个方法调用构造函数。对缓存的影响很小(valueOf 可能会为两个相等的值提供相同的对象引用,new 不会),但不会更多。

并且只是为了确保:Autoboxing/valueOf MIGHT 在使用两个相等的值调用它两次时给你相同的对象引用(至少如果你的值在 -128 和 127 之间),但这仍然使它成为通过 == 比较两个 Integer 对象是非常非常糟糕的主意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-05
    • 2017-01-31
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    相关资源
    最近更新 更多