布尔值查询

Boolean Value Query

有人能解释为什么这段代码给出了结果吗

public class InputTest {
    public static void main(String[] args) {
        Integer w = new Integer(1);
        Integer x = 1;
        Integer y = x;
        double z = x;
        System.out.println(w.equals(y));
        System.out.println(w == y);
        System.out.println(x == y);
        System.out.println(z == w);
    }}
w.equals(y)

returns true 因为 Integer.equals 比较 Integer 对象包装的值。


w == y

产生 false 因为你比较的是引用,而不是 Integer 对象包装的值。由于您显式创建了一个新的 Integer 对象 w (Integer w = new Integer(1)) wy 不是相同的对象。


x == y

产生 true,因为您将 x 分配给 y(y = x)。 xy 引用相同的 Integer 对象。


z == w

产生 true 因为比较中涉及的类型之一是原始类型; w 被拆箱并转换为 double(产生 1d)。在这个赋值中也是如此:double z = x;。比较这些原语产生 true.