• java 自动拆箱 自动装箱


    自动装箱的定义就是  基本数据类型赋值给包装类型,  拆箱则相反。   

    Integer integer = 122; // 自动装箱
    int num = integer; //自动拆箱
    

      

    想看一下源码是怎么完成自动装箱和拆箱的。 发现第一行代码自动装箱走的方法是 valueOf ,  看图

    这一段逻辑判断是, 如果传过来的值在Integer对象的缓存范围内,  就直接返回缓存好了的值, 否则另外新建一个Integer实例。

    小结:Integer缓存了一个装有255个数值的Integer数组, 在内部静态类IntegerCache的常量Integer[] cache中, 如果要装箱的值在缓存中就直接用传过来的值和IntegerCache常量low取得cache中与传过来的值对应的的下标

    先来看一下Integer的缓存, 以下是Integer 的部分源码

     1 /**
     2      * Cache to support the object identity semantics of autoboxing for values between
     3      * -128 and 127 (inclusive) as required by JLS.
     4      *
     5      * The cache is initialized on first usage.  The size of the cache
     6      * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     7      * During VM initialization, java.lang.Integer.IntegerCache.high property
     8      * may be set and saved in the private system properties in the
     9      * sun.misc.VM class.
    10      */
    11 
    12     private static class IntegerCache {
    13         static final int low = -128;
    14         static final int high;
    15         static final Integer cache[];
    16 
    17         static {
    18             // high value may be configured by property
    19             int h = 127;
    20             String integerCacheHighPropValue =
    21                 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
    22             if (integerCacheHighPropValue != null) {
    23                 try {
    24                     int i = parseInt(integerCacheHighPropValue);
    25                     i = Math.max(i, 127);
    26                     // Maximum array size is Integer.MAX_VALUE
    27                     h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
    28                 } catch( NumberFormatException nfe) {
    29                     // If the property cannot be parsed into an int, ignore it.
    30                 }
    31             }
    32             high = h;
    33 
    34             cache = new Integer[(high - low) + 1]; //如果不+1,k就<=
    35             int j = low;
    36             for(int k = 0; k < cache.length; k++)
    37                 cache[k] = new Integer(j++);
    38 
    39             // range [-128, 127] must be interned (JLS7 5.1.7)
    40             assert IntegerCache.high >= 127;
    41         }
    42 
    43         private IntegerCache() {}
    44     }

    源码中解释, 缓存是用来支持自动装箱的对象标识语义 , 它的值介于-128 (low)到127(high)之间, 且是在初次使用的时候被初始化掉

    也就是说在使用Integer的时候就已经缓存好了一段 [-128,-127......254,255] 这样的 Integer数组.   那么之前的自动装箱的valueOf的方法就可以豁然开朗了。 

    接下来看自动拆箱调用的方法intValue

    直接返回整型

  • 相关阅读:
    Servlet CDI Example Analysis
    JSON续
    JSON
    Ubuntu 下安装 MySQL
    Filter介绍
    Annotation相关
    Container、Injection
    Java buildTools
    Http协议
    URI URL URN 的区别
  • 原文地址:https://www.cnblogs.com/jxlsblog/p/9776090.html
Copyright © 2020-2023  润新知