2015-06-15 30 views
0

我知道我比较引用,而我使用==这不是一个好主意,但我不明白为什么会发生这种情况。为什么使用==两个整数的比较有时有效,有时不会?

Integer a=100; 
Integer b=100; 
Integer c=500; 
Integer d=500; 
System.out.println(a == b); //true 
System.out.println(a.equals(b)); //true 
System.out.println(c == d); //false 
System.out.println(c.equals(d)); //true 
+0

是的它是重复的!我在这里得到了完美的答案http://stackoverflow.com/questions/10002037/comparing-integer-values-in-java-strange-behavior。谢谢你们。 – Hiru

回答

10

Java语言规范说,至少从-128到127的包装对象缓存和Integer.valueOf(),这是隐含使用自动装箱重用。

0

正在缓存-128到127之间的整数值。

见下面的源代码:

private static class IntegerCache { 
    private IntegerCache(){} 

    static final Integer cache[] = new Integer[-(-128) + 127 + 1]; 

    static { 
     for(int i = 0; i < cache.length; i++) 
      cache[i] = new Integer(i - 128); 
    } 
} 

public static Integer valueOf(int i) { 
    final int offset = 128; 
    if (i >= -128 && i <= 127) { // must cache 
     return IntegerCache.cache[i + offset]; 
    } 
    return new Integer(i); 
} 
+0

==始终有效... –

+0

a == b返回true表示a和b引用相同的对象。 c == d返回false意味着c和d不是同一个对象(即使它们的intValue相同) –

+0

是绝对正确的Mastov ....最初我也感到困惑...请删除关于此帖的无关评论。谢谢大家 –

1

缓存-128和127之间的整数(整数相同的值引用相同的Object)。比较你的ab参考返回true,因为它们是相同的Object。您的cd不在该范围内,因此其参考比较返回false

相关问题