八种基本数据类型的大小,以及他们的封装类

八种基本数据类型的大小,以及他们的封装类

boolean
    Boolean
    byte- char - int - long - float -double
          short
    Byte -Character-Integer-Long-Float-Double
          Short

封装的作用

装箱应该理解为封装对象,即把基础数据类型(如 int)转换成基础类型封装类的对象(如 new Integer()) 拆箱就是装箱的反过程,即把基础类型封装类的对象(如 new Integer())转换为基础数据类型(如 int)。

List等集合类里面方的都是Object类型,为了让基本类型也具有对象的特征,
就出现了包装类型当我们传入基本数据类型时就会进行自动包装。

如果装箱时值在-128到127之间,之间返回常量池中的已经初始化后的Integer对象    
Integer c=123;
Integer d=123;  
c==d   //true

Integer.valueof()

  public static Integer valueOf(inti) {  
      if(i >= -128 &&i <=IntegerCache.high)  
         //如果i在-128~high之间,就直接在缓存中取出i的Integer类型对象
         return IntegerCache.cache[i + 128];  
      else
         return new Integer(i); //否则就在堆内存中创建 
}

IntegerCache 方法

private static class IntegerCache {//内部类,注意它的属性都是定义为static final
  static final inthigh; //缓存上界
  static final Integer cache[];//cache缓存是一个存放Integer类型的数组

  static {//静态语句块
      final int low = -128;//缓存下界,值不可变

      // high value may beconfigured by property
      int h = 127;// h值,可以通过设置jdk的AutoBoxCacheMax参数调整(参见(3))
      if (integerCacheHighPropValue !=null) {
          // Use Long.decode here to avoid invoking methods that
          // require Integer's autoboxing cache to be initialized
          // 通过解码integerCacheHighPropValue,而得到一个候选的上界值
          int i = Long.decode(integerCacheHighPropValue).intValue();
          // 取较大的作为上界,但又不能大于Integer的边界MAX_VALUE
          i = Math.max(i, 127);//上界最小为127
          // Maximum array size is Integer.MAX_VALUE
          h = Math.min(i, Integer.MAX_VALUE - -low);
      }
      high = h; //上界确定,此时high默认一般是127
      // 创建缓存块,注意缓存数组大小
      cache =new Integer[(high - low) + 1];
      int j = low;
      for(int k = 0; k <cache.length; k++)
          cache[k] =new Integer(j++);// -128到high值逐一分配到缓存数组
  }

  private IntegerCache() {}//构造方法,不需要构造什么
}

Last updated