gpt4 book ai didi

java - 初始化包装对象

转载 作者:行者123 更新时间:2023-12-02 04:38:02 24 4
gpt4 key购买 nike

怎么样Integer x1 = 5;不同于Integer x1 = new Integer(5);

Integer x1 = 5; // created through boxing
Integer x2 = 5;
Integer x3 = new Integer(5); // no boxing
Integer x4 = new Integer(5);
if (x1 == x2) System.out.println("Same object"); //prints
if (x3 == x4) System.out.println("Same object"); //doesn't print

正如我所预期的那样,此代码不会显示相同的对象两次。为什么?

PS:规则是:为了节省内存,以下包装对象的两个实例当它们的原始值相同时总是==:Boolean;字节;字符从\u 到\u007f;从 -128 到 127 的短整型

最佳答案

// Prints because of autoboxing ie it converts to integer value.
if (x1 == x2) System.out.println("Same object");
/*
* Doesn't prints because of creating an object(x3) using Integer wrapper class
* which is different from other object x4. ie both are different object
* pointing to different memory location in memory.
*/
if (x3 == x4) System.out.println("Same object");

关于java - 初始化包装对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30526394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com