Sat*_*h S 5 java object increment
任何人都可以告诉我输出变化的原因.
public class Demo {
public void demo()
{
Integer y = 567;
Integer x = y;
System.out.println(x + " " + y);
System.out.println(y == x);
y++;
System.out.println(x + " " + y);
System.out.println(y == x);
y--;
System.out.println(x + " " + y);
System.out.println(y == x);
}
public static void main(String args[])
{
Demo obj = new Demo();
obj.demo();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
567 567
true
567 568
false
567 567
False
Run Code Online (Sandbox Code Playgroud)
这就是为什么我得到最后的错误.
您正在使用Integer哪个是不可变对象.
基本上你的代码是
y = new Integer(y.intValue() + 1);
Run Code Online (Sandbox Code Playgroud)
和
y = new Integer(y.intValue() - 1);
Run Code Online (Sandbox Code Playgroud)
因此,您要创建两个与前一个对象不同的新Integer对象(==).
此行为在Java中称为自动装箱.
Integer y = 567; // y=567
Integer x = y; // x is equal to y object
System.out.println(x + " " + y); // out put x and y so obviously x and y are 567
System.out.println(y == x); // here x and y are in same reference. so this x==y is true and out put is true.
y++; // increment y by 1. then y=568
System.out.println(x + " " + y); // now x= 567 and y= 568
System.out.println(y == x);// now x not equals to y then false will print
y--; // again decrement y value
System.out.println(x + " " + y); // again x and y are same 567
System.out.println(y == x);// here y.value == x.value but x and y object wise not equal since object x and y are referring deference points
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2813 次 |
| 最近记录: |