《深入理解Java虚拟机》中的阐述Java语法糖的有关自动装箱的例子如下:public class AutoPack { public static void main(String[] args) {
// TODO Auto-generated method stub
Integer a=1;
Integer b=2;
Integer c=3;
Integer d=3;
Integer e=321;
Integer f=321;
Long g=3L;
System.out.println("c==d is:"+(c==d));
System.out.println("e==f is:"+(e==f));
System.out.println("c==(a+b)d is:"+(c==(a+b)));
System.out.println("c.equals(a+b) is:"+(c.equals(a+b)));
System.out.println("g==(a+b) is:"+(g==(a+b)));
System.out.println("g.equals(a+b) is:"+(g.equals(a+b))); }}
输出结果如下:
c==d is:true
e==f is:false
c==(a+b)d is:true
c.equals(a+b) is:true
g==(a+b) is:true
g.equals(a+b) is:false疑问主要有两点:
1.c==d和e==f无论类型还是数值应该都是一样的,为什么c==d返回的是true,而e==f返回的false?
2c.equals(a+b)和g.equals(a+b)的自动装箱是怎么样的,和1有同样的疑问,返回的结果为什么是不同的?

解决方案 »

  1.   

    补充一下JDK的版本信息如下:
    java version "1.6.0_45"
    Java(TM) SE Runtime Environment (build 1.6.0_45-b06)
    Java HotSpot(TM) 64-Bit Server VM (build 20.45-b01, mixed mode)
      

  2.   

    Integer -128 到127 是提前建好的,所以当你新建的值在这范围内就是直接引用这个建好的对象。所以c和d其实指向同一个内存地址。e和f就不是同一地址,而是新建的。
      

  3.   

    equals 是值比较,但只能用作同类型的object作比较。 所以你Long 对比Integer就相当于对比null。然后就false。
      

  4.   

     /**
         * Cache to support the object identity semantics of autoboxing for values between 
         * -128 and 127 (inclusive) as required by JLS.
         *
         * The cache is initialized on first usage. During VM initialization the
         * getAndRemoveCacheProperties method may be used to get and remove any system
         * properites that configure the cache size. At this time, the size of the
         * cache may be controlled by the vm option -XX:AutoBoxCacheMax=<size>.
         */    // value of java.lang.Integer.IntegerCache.high property (obtained during VM init)
        private static String integerCacheHighPropValue;
      

  5.   

    综合上面的,equals是比较地址,当然类型不同的话,肯定地址是不同的,所以就能解释你的问题了!
      

  6.   

    因为你是直接把常量赋值给了Integer
    而不是Integer c = new Integer(3);
      

  7.   

    考点就是-128到127以外的数,new的内存地址是不一样的
      

  8.   

    哦,原来是这样,了解了。再问一个问题,为什么-128到127,Java虚拟机为什么要这样设计?我只看到iconst字节码指令是0到5的资料,其他好像没什么文档说明。
      

  9.   

    equals比较是类型和值吧,==才是比较地址吧。
      

  10.   

    equals比较是类型和值吧,==才是比较地址吧。恩,没注意打错了!不过在Object中为改写的时候的确是看hash码的!~