0

为什么在比较 Long、Integer 等原始包装类时不使用 ==。为什么它们不起作用。

public static void main(String[] args) {

        Number l = Integer.parseInt("30");
        Number l2 = Integer.parseInt("30");
        System.out.println(l == l2);        

        l = Integer.parseInt("3000");
        l2 = Integer.parseInt("3000");
        System.out.println(l == l2);
    }

为什么在上面的代码中一个结果为真而另一个为假???

4

4 回答 4

2

首先,警告: 您不是在比较值;您正在比较内存地址。

The wrapper classes are still bonafide objects - and the only way to test object equality is to the the equals() method. If you were comparing against a compatible* primitive, then auto-unboxing would have taken the Integer into an int, and did an equality check on that. Note that Number can't be auto-unboxed; you would have to call intValue() to get an int back.

Second, Integer.valueOf() will cache values in a byte range, from -128 to 127. Any two Integer objects instantiated within that range will resolve to the same memory address.

*: Either one of those Number objects would need to become an int.

于 2013-03-30T06:04:48.553 回答
2

Consider this case:

 new Integer(30)==new Integer(30) 

On each side of == you have a new instance, then the left hand side and the right hand side are different objects, and the comparison evaluates as false (as it tests instance identity).

The case with boxing is more complicate, as it relies on Integer.valueOf, which already caches the value for some low-value integers (at least in the range -128 to 127, though implementations can choose a greater range).

This issue is similar to the following, where the equality evaluates as true even when we have been told that we should compare strings using equals.

String a = "foo";
String b = "foo";
System.out.println(a==b);
于 2013-03-30T06:15:15.623 回答
1

这些行

Number l = Integer.parseInt("30");
Number l2 = Integer.parseInt("30");

由 Java 编译器(自动发件箱)转换为

Number l = Integer.valueOf(Integer.parseInt("30"));
Number l2 = Integer.valueOf(Integer.parseInt("30"));

Integer.valueOf(int) API 说此方法将始终缓存 -128 到 127 范围内的值,包括. 也就是说,对于 30 个,从缓存中返回相同的 Integer 实例;对于 3000,返回 Integer 的两个不同(新)实例。

于 2013-03-30T05:44:19.687 回答
1

According to java specification java language specification

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

于 2020-06-19T14:31:18.097 回答