Integer类实现方式和注意事项

java.lang.Integer类的源代码:

//定义一个长度为256的Integer数组
static final Integer[] cache = new Integer[-(-128) + 127 + 1];
static {
      //执行初始化,创建-128到127的Integer实例,并放入cache数组中
      for(int i = 0; i < cache.length; i++) {
            cache[i] = new Integer(i - 128);
      }      
}

从上面代码可以看出,系统把一个-128~127之间的整数自动装箱成Integer实例,并放入了一个名为cache的数组中缓存气力啊。如果以后把一个-128~127之间的整数自动装箱成一个Integer实例时,实际上是直接指向对应的数组元素,因此-128~127直接的同一个整数自动装箱成Integer实例时,永远都是引用cache数组的同一个数组元素,所以他们全部相等;但每次把一个不再-128~127范围内的整数自动装箱成Integer实例时,系统总是重新创建一个Integer实例,所以会出现下面代码的运行结果:

//通过自动装箱,允许把基本类型值赋值给包装类实例
Integer ina = 2;
Integer inb = 2;//输出true
System.out.println("两个2自动装箱后是否相等:" + (ina == inb));

Integer biga = 128;
Integer bigb = 128;
//输出false
System.out.println("两个128自动装箱后是否相等:" + (biga == bigb));

猜你喜欢

转载自www.cnblogs.com/wgl1995/p/9282977.html