首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

蛋痛的JAVA比较相等符号(java里的潜规则)

2012-12-25 
蛋疼的JAVA比较相等符号(java里的潜规则)/* Hello.java */import java.lang.Integerpublic class Hello{p

蛋疼的JAVA比较相等符号(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个输出结果会是什么。。。

结果:
true
false
true

原因:
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);
    }



热点排行