2013-07-08 106 views
5

任何人都可以告诉我输出更改的原因。递增和递减更改对象值

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(); 
    } 
} 

输出

567 567 

true 

567 568 

false 

567 567 

False 

这里为什么我得到最终假的。

+2

尝试y.equals(x)而不是==。 – gcandal

回答

1
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 
+0

错误,'=='**总是**做对象引用检查。对第二个“假”的解释是不正确的。 –

+0

@BuhakeSindi我的意思是。但你错了。现在我改变一些话 –

0

因为x和y指的是2个不同的对象。

y--; 

这首先将y解释为int,而不是递减它,而不是将它放到Integer中。这个新的盒装整数指的是不同的内存位置。

理想情况下,在包装类上,它最好在包装对象而不是==运算符上调用equals方法。

0

y == x检查内容是否相等,即它们是否指向相同的对象,而不是它们指向的对象是否包含相同的int。特别是当x, y >= 128

使用

y.equals(x); 

(int) y == (int) x 

或声明xyint代替。

请注意,自动拆箱不会发生在Integer == IntegerInteger != Integer

3

更改

Integer y = 567; 
    Integer x = y; 

int y = 567; 
    int x = y; 

和suprprising行为将不复存在。我的猜测是,你已经偶然发现Java的隐含原始值隐含自动装箱到包装对象,并导致相信你直接操纵数字。

0

当您使用原始int而不是Integer。最终的输出将是true

但是,当您使用Integer类时,这些是Object s。如果使用equals方法,最终输出将为true

+0

'当你使用Integer而不是原始的int。最终的结果是真的。什么? –

+0

@BuhakeSindi - Typo。 – JHS

5

您正在使用Integer这是一个不可变的对象。

基本上你的代码是

y = new Integer(y.intValue() + 1); 

y = new Integer(y.intValue() - 1); 

因此要创建两个新的Integer对象是不一样的(==)作为前述目的。

这种行为在Java中被称为自动装盒

+1

编译器将使用'Integer.valueOf()'而不是构造函数。 –

+0

@BuhakeSindi我使用构造函数使其更加清晰,而不是显示JVM在做什么。 –

2

这是因为编译器这个内部:

y-- 

表示:

int _y = y.intValue(); 
_y--; 
y = Integer.valueOf(_y); 

因此,y是有一个新的Integer实例。你正在做对象引用检查(当使用==时)而不是值相等检查。使用equals()方法来评估2个值。

-1

甚至,如果你创建

Integer a = new Integer(1000); 
Integer b = new Integer(1000); 

一个== b - 假

Integer a = new Integer(1); 
Integer b = new Integer(1); 

一个== b - 是真的

,在Java中一个小整数的缓存:-127到128.所有其他整数是新创建的对象,它们不能等于。

+0

在Java中,new'operator ** always **为新对象分配内存。这与'public static Integer valueOf(int i)'方法相反,该方法从内部缓存中获取您的答案中指定范围的整数,否则返回一个新整数。 – skuntsel