自动拆箱和装箱(一)


为什么会需要包装类型

  我们知道Java是一个面相对象的编程语言,基本类型并不具有对象的性质,为了让基本类型也具有对象的特征,就出现了包装类型(如我们在使用集合类型Collection时就一定要使用包装类型而非基本类型),它相当于将基本类型“包装起来”,使得它具有了对象的性质,并且为其添加了属性和方法,丰富了基本类型的操作。
  当需要往ArrayList,HashMap中放东西时,像int,double这种基本类型是放不进去的,因为容器都是装object的,这是就需要这些基本类型的包装器类了。
Java的基本类型(元数据)与对应的包装类型:

基本类型基本类型大小包装类型
byte1个字节Byte
shot2个字节Short
int4个字节Integer
long8个字节Long
float4个字节Float
double8个字节Double
char取决于底层保存的字符Character
booleanBoolean

包装类的缺点:
  在 64 位的 Java 虚拟机中,每一个 Java 对象在内存中的额外开销就最少是16 个字节。以 Integer 类为例,它仅有一个 int 类型的私有字段,占 4 个字节。因此,每一个 Integer 对象的额外内存开销至少是int的400%

什么是自动装箱和拆箱

自动装箱:将基本的类型数据转换为对应的包装包装类型数据

Integer a = 1;//装箱

自动拆箱:将包装类型转换为基本类型数据
int b = a; //拆箱

自动拆箱和装箱的实现

下面是很简单的自动装箱与自动拆箱的代码,进过反编译结果在下图:
image_1clir1vt713ib1nsd2h91k8um0s9.png-30.1kB

当进行自动装箱时代用的是valueOf()方法

image_1clj2i1g14gi1ur41a2tkcd1hn84a.png-26.1kB

当进行自动拆箱时,代用的是intValue()方法

image_1clj2kv77mnt1i9sfptm019uk4n.png-22.9kB

IntegerCahe分析

IntegerCache的详细可以看:https://blog.csdn.net/zx6571269/article/details/82026879 这篇文章是转载的个人感觉写的非常好
Integer里面只有一个value属性.
image_1clkunjif16an1g0i1p2p1a8l18unp.png-4.3kB

swap主要用于交换两个Integer对象在栈里面的数据。

private  static void swap(Integer a,Integer b) throws NoSuchFieldException, IllegalAccessException {
        Field valueField = Integer.class.getDeclaredField("value");
        valueField.setAccessible(true);
        int temp = valueField.getInt(a);
        valueField.setInt(a,b.intValue());
        valueField.setInt(b,temp);
    }
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Integer a=1,b=2;
        swap(a,b);
        System.out.println("a=:"+a);
        System.out.println("b=:"+b);

        Integer c=1;
        System.out.println("c=:"+c);
        System.out.println("b=:"+b);
    }

大家可以猜猜结果:
image_1cll0eouh3t11ir01rfp1lau1qi91j.png-12.4kB

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 {@code -XX:AutoBoxCacheMax=<size>} 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.
     */
 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;
            //查找JVM,Integer初始化的缓存设置
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;
            //创建缓存数组
            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

  IntegerCache是一个静态的内部类,当,第一次初始化化是,,int c = 1反编译后的Integer c = Integer.valueOf((int)1);其中java.lang.Integer.IntegerCache.high的取值范围,它默认的范围是[-128,127]之间。在该区间内所有的Integer.valueOf(int)函数返回的对象,是根据int值计算的偏移量,从数组Integer.IntegerCache.cache中获取,对象是同一个,不会新建对象。所以当我们修改了Integer.valueOf(1)的value后,所有Integer.IntegerCache.cache[ 1 - IntegerCache.low ]的返回值都会变更。

包装类是否有Cache范围
ByteByteCache[-128,127](固定)
ShortShortCache[-128,127](固定)
intIntegerCache[-128,Integer.MAX_VALUE - (-low) -1]
longLongCache[-128,127](固定)
float
Double
CharacterCharacterCache[0,127]
Boolean

参考1:https://www.jb51.net/article/129640.htm
参考2:https://www.cnblogs.com/dolphin0520/p/3780005.html
参考3:https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值