懒码农。。。。。。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

转自:http://www.iteye.com/topic/1116623

/* 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); 
  } 

 

结果:

 

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);
    }
 

posted on 2011-10-18 12:19  阿彬  阅读(351)  评论(0)    收藏  举报