美文网首页
Integer的equals ==

Integer的equals ==

作者: 尔乐 | 来源:发表于2017-03-07 19:15 被阅读24次

equals比较的是 Integer.intValue的数值。
==比较的是对象的引用。

public boolean equals(Object obj){
    if(obj instanceof Integer){
        return value==((Integer)obj).intValue();
    }
    return false;
}
//在做 Integer i3 =100;时系统执行了自动封箱,此时会执行valueOf方法。
public static Integer valueOf(int i){
    if(i>=IntegerCache.low&&i<=IntegerCache.high)
        return IntegerCache.cache[i+(-IntegerCache.low)];
    return new Integer(i);
}
//我们看到在IntegerCache.low和IntegerCache.high之间的IntegerJava使用了缓存,其他的数值,会重新new Integer出来。
//测试代码
public static void main(String[] args){
    Integer i1 =200;
    Integer i2 =200;
    System.out.println("i1==i2: "+(i1==i2));
    // 在-128~127 之内的数
    Integer i3 =100;
    Integer i4 =100;
    System.out.println("i3==i4: "+(i3==i4));
    }

相关文章

网友评论

      本文标题:Integer的equals ==

      本文链接:https://www.haomeiwen.com/subject/qxzmgttx.html