1 public static void main(String[] args) {
 2     int i1 = 128;
 3     Integer i2 = 128;
 4     Integer i3 = new Integer(128);
 5     System.out.println(i1 == i2);//true
 6     System.out.println(i1 == i3);//true
 7     System.out.println("**************************************");
 8     Integer i4 = 127;
 9     Integer i5 = 127;
10     Integer i6 = 128;
11     Integer i7 = 128;
12     System.out.println(i4 == i5);//true
13     System.out.println(i6 == i7);//false
14     System.out.println("**************************************");
15     Integer i8 = new Integer(127);
16     Integer i9 = new Integer(127);
17     System.out.println(i8 == i9);//false
18     System.out.println(i8.equals(i9));//true
19     System.out.println(i4 == i8);//false
20     /* Output:
21         true
22         true
23         **************************************
24         true
25         false
26         **************************************
27         false
28         true
29         false
30      */
31 }
  1. 第5和第6行的结果都为true。因为Integer与int比较时,Ingeger都会自动拆箱(jdk1.5以上)。
  2. 第12行结果为true,第13行结果为false。
    因为Java在编译的时候,Integer i4=127被翻译成-> Integer i4= Integer.valueOf(127);
    JDK源码:
    /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} 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.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
    View Code

     看一下源码大家就会明白,对于-128到127之间的数,会进行缓存,Integer i6 = 127时,会将127进行缓存,下次再写Integer i7 = 127时,就会直接从缓存中取,就不会new了。

  3. i8、i9使用的是new, 对象不一样,所以第17行结果为false,第18行结果为true ,第19行结果为false。

总结

  1. Ingeter是int的包装类,int的初值为0,Ingeter的初值为null。
  2. 无论如何,Integer与new Integer()不会相等。不会经历拆箱过程,i8的引用指向堆,而i4指向专门存放他的内存(常量池),他们的内存地址不一样,使用 == 比较都为false。
  3. 两个都是非new出来的Integer,使用 == 比较,如果数在-128到127之间,则是true,否则为false
  4. 两个都是new出来的,==比较都为false。若要比较值是否相等,需使用equals方法进行比较。
  5. int和Integer(无论new否)比,都为true,因为会把Integer自动拆箱为int再去比。

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程

4301 9.8元 98元 1折
3678 0元 限免