java的自动拆箱和装箱的简介

一. java的自动拆装箱在 1.5 以后引入

二. 因为java的一切皆对象, 包装类型简单的理解就是将 基本数据类型转换成了 包装类型 , 拥有了对象的特点,有了一些属性和方法

三. 自动拆装箱在编译阶段就发生了. 只是一个编译的语法糖.

自动装箱和自动拆箱其实是Java编译器提供的一颗语法糖(语法糖是指在计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。通过可提高开发效率,增加代码可读性,增加代码的安全性)

四. 实现拆装箱的方法

装箱过程是通过调用包装器的valueOf方法实现的,而拆箱过程是通过调用包装器的 xxxValue方法实现的。(xxx代表对应的基本数据类型

	Integer integers = 10;  //装箱
	Integer localInteger = Integer.valueOf(10); //源码实现反编译
	
	int n = integers;   //拆箱
	int i = localInteger.intValue(); //源码实现反编译

Integer的源码.

/**
     * 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;
            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() {}
    }

    /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

五. 对于拆装箱的一些问题

  1. 看过上面的源码以后不知道, 有没有什么感觉. 那就拿一个常见的问题来进行加深印象.
public class Test {
    public static void main(String[] args) {
         
        Integer i1 = 100;
        Integer i2 = 100;
        Integer i3 = 200;
        Integer i4 = 200;
        
        System.out.println(i1==i2);
        System.out.println(i3==i4);
    }
}

输出结果:
.
.猜猜看
.
.
.常被问
.
.
.就问到 自动拆装箱, 或者由 , 引出自动拆装箱的问题就是这个
.
.
.

true
false

输出结果表明i1和i2指向的是同一个对象,而i3和i4指向的是不同的对象。

由上面的源码缓存得到的结果也不难.


以上是integer的包装类的部分源码


那么同样的.看 Double的包装类型

public class Main {
    public static void main(String[] args) {
         
        Double i1 = 100.0;
        Double i2 = 100.0;
        Double i3 = 200.0;
        Double i4 = 200.0;
         
        System.out.println(i1==i2);
        System.out.println(i3==i4);
    }
}

.
.
.这个结果,再猜猜看
.
.
.聪明的你一定会想到,肯定不一样了
.
.
.为什么不一样呢?
.
.
.

false
false

.看Double的源代码

/**
     * Returns a {@code Double} instance representing the specified
     * {@code double} value.
     * If a new {@code Double} instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Double(double)}, as this method is likely to yield
     * significantly better space and time performance by caching
     * frequently requested values.
     *
     * @param  d a double value.
     * @return a {@code Double} instance representing {@code d}.
     * @since  1.5
     */
    public static Double valueOf(double d) {
        return new Double(d);
    }

就很简单粗暴, 直接 new 一个 Double 的对象出来, 使用有参构造来创建.

/**
     * Constructs a newly allocated {@code Double} object that
     * represents the primitive {@code double} argument.
     *
     * @param   value   the value to be represented by the {@code Double}.
     */
    public Double(double value) {
        this.value = value;
    }

每一个创建的Double的包装类都是新得对象, 所以就是每一个都是全新的对象.

注意,Integer、Short、Byte、Character、Long这几个类的valueOf方法的实现是类似的。
.
Double、Float的valueOf方法的实现是类似的。


以上是Double类型的包装类


public class Main {
    public static void main(String[] args) {
         
        Boolean i1 = false;
        Boolean i2 = false;
        Boolean i3 = true;
        Boolean i4 = true;
         
        System.out.println(i1==i2);
        System.out.println(i3==i4);
    }
}

.
.
.这个结果,再猜猜看
.
.
.聪明的你一定会想到,肯定还是不一样了
.
.
.为什么不一样呢?
.
.
.

true
true

Boolean的源码

	public static Boolean valueOf(boolean b) {
		return (b ? TRUE : FALSE);
	}
	public static final Boolean TRUE = new Boolean(true);

    /** 
     * The <code>Boolean</code> object corresponding to the primitive 
     * value <code>false</code>. 
     */
    public static final Boolean FALSE = new Boolean(false);

以上是Boolean类型的包装类


public class Main {
    public static void main(String[] args) {
         
        Integer a = 1;
        Integer b = 2;
        Integer c = 3;
        Integer d = 3;
        Integer e = 321;
        Integer f = 321;
        Long g = 3L;
        Long h = 2L;
         
        System.out.println(c==d);
        System.out.println(e==f);
        System.out.println(c==(a+b));
        System.out.println(c.equals(a+b));
        System.out.println(g==(a+b));
        System.out.println(g.equals(a+b));
        System.out.println(g.equals(a+h));
    }
}

那这个输出的结果?

先别看输出结果,读者自己想一下这段代码的输出结果是什么。这里面需要注意的是:当 "=="运算符的两个操作数都是 包装器类型的引用,则是比较指向的是否是同一个对象,而如果其中有一个操作数是表达式(即包含算术运算)则比较的是数值(即会触发自动拆箱的过程)。另外,对于包装器类型,equals方法并不会进行类型转换。明白了这2点之后,上面的输出结果便一目了然:

true
false
true
true
true
false
true

倒数第二个很多人有疑问?

那去看源码呗.
Long类型的equals的源码来看.

/**
     * Compares this object to the specified object.  The result is
     * {@code true} if and only if the argument is not
     * {@code null} and is a {@code Long} object that
     * contains the same {@code long} value as this object.
     *
     * @param   obj   the object to compare with.
     * @return  {@code true} if the objects are the same;
     *          {@code false} otherwise.
     */
    public boolean equals(Object obj) {
        if (obj instanceof Long) {
            return value == ((Long)obj).longValue();
        }
        return false;
    }

首先会进行 instanceof 类型转换的判断, 当比较前后的两个数据类型不一致时, 直接退出了, 返回 false 所以喽.

g 为 long , (a+b)是先拆箱成为两个 int型的数据进行加法操作, 得到的结果再装箱成 integer 类型 , 然后进行数据的比较就出现了 类型转换的失败.

那么最后一个为什么又对了呢?

原因是这样的:

g 为 Long 类型的, 然后将 a 拆箱成 int 型的数值, 再将 h 拆箱成 long 这两个基本类型, 当进行 int + long 的时候 int 自动升级为了 long 类型, 两个 long 基本类型加完了以后还是 long 类型的数值, 接着 又自动装箱成了 Long的包装类型 , 进行数值的比较, 所以为 true .

完结!

如果有哪位朋友有补充的内容,欢迎下方留言,不胜感激!

真大佬
参考文档 = https://www.cnblogs.com/dolphin0520/p/3780005.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值