论坛首页 Java企业应用论坛

蛋疼的JAVA比较相等符号

浏览 16754 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (3) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-10-16  
前2天看了一个PPT,很好玩,居然有这么一道陷阱的JAVA题:

/* Hello.java */
import java.lang.Integer;

public class Hello
{
  public static void main(String[] args)
  {
    int a = 1000, b = 1000;
    System.out.println(a == b);

    Integer c = 1000, d = 1000;
    System.out.println(c == d);

    Integer e = 100, f = 100;
    System.out.println(e == f);
  }
}

大家不要去运行程序,先想想,上述3个输出结果会是什么。。。
经过这道题后,我再也不相信“爱情”了,哈哈。
   发表时间:2011-10-16  
true
false
true

出这种题的人是白痴。
0 请登录后投票
   发表时间:2011-10-17   最后修改:2011-10-17
这叫什么陷阱,那是某些人自己踩钢丝失足了。
做语义相等比较,只要能用equals,一律用equals
就算对象的语义相等就是引用相等,那也应该把equals覆盖了,把==的判断写到equals里
不过如果能确定当前对象和它的所有超类从来没有覆盖过equals的话,Object上的equals就是==

关于boxing类型,实际见得最多的陷阱是:
private Boolean cond
....
if (cond) {
   ...
}
有可能会抛空指针
0 请登录后投票
   发表时间:2011-10-17  
wumingshi 写道
true
false
true

出这种题的人是白痴。

为啥中间是false?1000和100的integer对象不同?
0 请登录后投票
   发表时间:2011-10-17  
Integer类型 默认-128~127使用缓存数据, 在默认的范围内使用的是同一对象,所以相等,否则不等
    /**
     * Returns a <tt>Integer</tt> instance representing the specified
     * <tt>int</tt> value.
     * If a new <tt>Integer</tt> instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Integer(int)}, as this method is likely to yield
     * significantly better space and time performance by caching
     * frequently requested values.
     *
     * @param  i an <code>int</code> value.
     * @return a <tt>Integer</tt> instance representing <tt>i</tt>.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if(i >= -128 && i <= IntegerCache.high)
            return IntegerCache.cache[i + 128];
        else
            return new Integer(i);
    }
1 请登录后投票
   发表时间:2011-10-17  
LS是正确的,这是java里的潜规则了
0 请登录后投票
   发表时间:2011-10-17  
iOracleSun 写道
wumingshi 写道
true
false
true

出这种题的人是白痴。

为啥中间是false?1000和100的integer对象不同?


100在静态初始化缓存范围中
0 请登录后投票
   发表时间:2011-10-17  
wumingshi 写道
true
false
true

出这种题的人是白痴。

坦诚的讲,这题我之前还真不知道,受教了
0 请登录后投票
   发表时间:2011-10-17  
额,牛B,真不知道!
Java在这里确实有问题啊,至少语义和实现上不统一,这要是出了问题找都找不出来,非要看JDK源码不可。
0 请登录后投票
   发表时间:2011-10-17  
看到楼主,想到我的一个同事,很傻很天真。
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics