JAVA Integer值的范围

原文出处:http://hi.baidu.com/eduask%C9%BD%C8%AA/blog/item/227bf4d81c71ebf538012f53.html

package com.test;
public class Test {
   public static void main(String []args) {
     Integer a = 100;//此处若使用new,则==值必为false
     Integer b = 100;
     System.out.println(a==b);//true
     Integer c = 150;
     Integer d = 150;
     System.out.println(c==d);//false
   }
}

  这是什么原因呢?
  1。java在编译的时候 Integer a = 100; 被翻译成-> Integer a = Integer.valueOf(100);
  2。比较的时候仍然是对象的比较
  3。在jdk源码中

public static Integer valueOf(int i) { 
  final int offset = 128; 
  if (i >= -128 && i <= 127) { // must cache 
  return IntegerCache.cache[i + offset]; //符合值范围时候,进入也创建好的静态IntergerCache,i+offset的值表示去取cache数组中那个下标的值
  } 
  return new Integer(i); //当不符合-128 127值范围时候。记住用的:new,开辟新的内存空间,不属于IntergerCache管理区
} 

  而

private static class IntegerCache { 
  private IntegerCache(){} 
  static final Integer cache[] = new Integer[-(-128) + 127 + 1]; //开辟-128到127的内存区。有0的位置哦
  static { 
    for(int i = 0; i < cache.length; i++) 
      cache[i] = new Integer(i - 128); //为内存区的数组每个对象赋值
    } 
  } 

  这边是java为了提高效率,初始化了-128--127之间的整数对象,所以在赋值在这个范围内都是同一个对象。

  

  再加一句
  Integer a = 100;
  a++;
  //这边a++是新创建了一个对象,不是以前的对象。

    public static void main(String []args) {
        Integer a = 100;
        Integer b = a;//此时b指针指向值为100的堆地址  即a的堆地址,a==b成立
        a++;//此时a指向的值发生变化为101,a指针指向101的堆地址。而b任然指向100
        System.out.println(a==b);//false
    }


 

原文地址:https://www.cnblogs.com/alternative/p/7494869.html