Java 初始化包装对象
Java 初始化包装对象,java,wrapper,Java,Wrapper,整数x1=5不同于整数x1=新整数(5) 这段代码不会像我预期的那样显示同一个对象两次。为什么? PS:规则是:为了节省内存,以下包装器对象的两个实例在其原语值相同时始终为==布尔值;字节;字符从\u到\u007f;Short和Integer从-128到127看看新整数(5)如何返回一个已经存在的对象(如果想要相同的对象,它需要这样做)?它之所以被称为new,是有原因的。整数x1=5编译为整数x1=Integer.valueOf(5)如果要比较两个整数,请使用.equals;如果要澄清不等式,请
整数x1=5代码>不同于整数x1=新整数(5)代码>
这段代码不会像我预期的那样显示同一个对象两次。为什么?
PS:规则是:为了节省内存,以下包装器对象的两个实例在其原语值相同时始终为==布尔值;字节;字符从\u到\u007f;Short和Integer从-128到127看看新整数(5)
如何返回一个已经存在的对象(如果想要相同的对象,它需要这样做)?它之所以被称为new
,是有原因的。整数x1=5代码>编译为整数x1=Integer.valueOf(5)代码>如果要比较两个整数,请使用.equals;如果要澄清不等式,请显式写入强制转换:If((int)x1<(int)x4);您也可以这样做:x1。与(x2)<0/==x1整数x1=5555
。
// 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");
// 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");