当前位置: 移动技术网 > IT编程>开发语言>Java > java中Integer包装类装箱的一个细节详解

java中Integer包装类装箱的一个细节详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

前言

java有八个基本数据类型,每个都有对应的一个包装类,比如int对应的integer。 integer 是int的包装类型,数据类型是类,初值为null,从jdk1.5开始,java引入了自动拆装箱,可以直接进行形如integer i = 20形式的赋值,编译器会自动将其转换为integer i = integer.valueof(20)进行装箱,拆箱则是将int j = i的形式转换成了int j = i.intvalue()

装箱有个细节,如果不注意很容易出错,来看一下:

integer i = 20;
integer j = integer.valueof(20);

system.out.println(i == j);

上面的代码输出为

true

好像没什么问题,那我们形式不变,将数字20换成200,即

i = 200;
j = integer.valueof(200);

system.out.println(i == j);

同样的判断,输出变成了:

false

这是为什么呢?

先明确一点,经过编译器编译后,integer i = 20转换成了integer i = integer.valueof(20) ,和integer j = integer.valueof(20)的定义完全一样,那为什么将20换成了200后判断结果不一样了呢?

我们来看看integer.valueof(int i)方法的内部:

 public static integer valueof(int i) {
  assert integercache.high >= 127;
  if (i >= integercache.low && i <= integercache.high)
   return integercache.cache[i + (-integercache.low)];
  return new integer(i);
 }

可以看出当i在某个区间内时,直接返回了缓存数组integercache.cache中的一个值,超出区间才new一个新的integer对象。到这里我们大概就可以得出结论:20在缓存范围内所以直接用了缓存,但是200超出了缓存区间所以new了新对象,和原来对象的地址当然不会相同,所以返回false

再来看看integercache,这是一个integer的私有静态内部类,定义如下:

private static class integercache {
  static final int low = -128;
  static final int high;
  static final integer cache[];

  static {
   // high value may be configured by property
   int h = 127;
   string integercachehighpropvalue =
    sun.misc.vm.getsavedproperty("java.lang.integer.integercache.high");
   if (integercachehighpropvalue != null) {
    int i = parseint(integercachehighpropvalue);
    i = math.max(i, 127);
    // maximum array size is integer.max_value
    h = math.min(i, integer.max_value - (-low));
   }
   high = h;

   cache = new integer[(high - low) + 1];
   int j = low;
   for(int k = 0; k < cache.length; k++)
    cache[k] = new integer(j++);
  }

  private integercache() {}
 }

可以看出默认的缓存区间是-128~127,那么什么情况下会修改这个范围呢,修改了某个虚拟机参数的时候,通过代码也可看出,设置的这个缓存上限java.lang.integer.integercache.high值不能小于127,小于的话就会被赋予127,从而失效。
那么这个值怎么设置呢?我们来看看jdk源码中怎么解释integercache这个静态内部类:

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. the size of the cache may be controlled by the -xx:autoboxcachemax= option. during vm initialization, java.lang.integer.integercache.high property may be set and saved in the private system properties in the sun.misc.vm class.

大概意思是:

将-128到127(包含)的数字做缓存以供自动装箱使用。缓存在第一次使用时被初始化。大小可以由jvm参数-xx:autoboxcachemax=option来指定。jvm初始化时此值被设置成java.lang.integer.integercache.high属性并作为私有的系统属性保存在sun.misc.vm.class中。

可以得到结论:这个缓存的high值是由jvm参数 -xx:autoboxcachemax= option来指定的。

上述jdk源码来源于jdk1.7,不同版本实现略有不同,但思路一致。

这种共享常用对象的思路有一个名字,叫享元模式,英文名叫flyweight,即共享的轻量级元素。其他包装类如boolean、byte、short、long、charactor都有类似的实现。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网