自动拆装箱 equals和==区别

来源:互联网 发布:godaddy域名邮箱设置 编辑:程序博客网 时间:2024/05/29 05:56
class  IntegerDemo1
{
public static void main(String[] args) 
{
// Integer x = new Integer(4);


//Integer x = 4;//1.5新特性。自动装箱。相当于new Integer(4);
Integer x = null;//编译会失败,null不会调用方法。所以新特性健壮性很差,要判断是否为空。
x = x/*x.intValue()*/ + 2;//x+2;x进行自动拆箱。变成了int类型。和2进行加法运算。
//再将和进行装箱赋给x。
}


public static void method()
{
Integer x = new Integer("123");
Integer y = new Integer(123);


sop("x==y"+(x=y));//为假,因为是俩对象。所以false
sop("x.equals(y):"+x.equals(y));//Integer方法本身复写过equals方法,比较的是两个数是否相等。所以为true





Integer m = 128;
Integer n = 128;
sop("m==n:"+(m==n));//结果为false,新特性对于超过了byte范围(-128~127)就另开辟空间。




Integer a = 127;
Integer b = 127;
sop("a==b"+(a==b));//结果为true。因为a和b指向了同一个Integer对象。
//因为当数值在byte范围内时,对于新特性,如果该数值已经存在,则不会在开辟新的空间。
//所以相等。




}


public static void sop(String str)
{
System.out.println(str);
}
}
0 0
原创粉丝点击