[java]自动拆箱装箱

目录

前言

总结

示例代码

boolean

 Integer

练习题


前言

遇到问题,就亲自写一写,源码看看。

总结

比如integer:

Integer a = 11; 
系统自动帮我们执行: 
Integer a = Integer.valueOf(11);

int b = a; 
系统自动执行了: 
int b = a.intValue();

所以我们需要关注 valueOf 和 intValue;

原始类型:byte, short, char, int, long, float, double 和 boolean

对应的是:Byte, Short, Character, Integer, Long, Float, Double, Boolean。

为什么要有拆箱装箱呢?

java中为了减少对象的创建。

只有double和float的自动装箱代码没有使用缓存,每次都是new 新的对象,其它的6种基本类型都使用了缓存策略。

使用缓存策略是因为,缓存的这些对象都是经常使用到的(如字符、-128至127之间的数字),防止每次自动装箱都创建一此对象的实例。

(PS:因为double、float是浮点型的,没有特别的热的(经常使用到的)数据的)

Character创建了数值在[0,127]范围的缓存数据,Boolean 直接返回True Or False。

示例代码

boolean

测试:

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

 也没啥特别的。

因为java类中,boolean只有这两种情况,所以static final创建好了这东西。

{
    /**
     * The {@code Boolean} object corresponding to the primitive
     * value {@code true}.
     */
    public static final Boolean TRUE = new Boolean(true);

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

 Integer

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

上面的代码中,主要是有一个IntegerCache ,还有就是返回了一个新的new' 对象。

这段代码就是,如果他在-128 到127之间,那么我们就是用cache中的对象,不给它 new一个对象了。

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

维持了一个cache数组,

static静态方法,类加载的时候进行初始化cache[],静态变量存放在常量池中

该类静态初始化了一个包含了Integer.IntegerCache.lowjava.lang.Integer.IntegerCache.high的Integer数组。

其中java.lang.Integer.IntegerCache.high的取值范围在[127~Integer.MAX_VALUE - (-low) -1]之间。

都放到了Integer cache[];

这部分初始化的时候就做好了~

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

我就有个问题,为什么最大值一定要从配置中去读?

String integerCacheHighPropValue =
    sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");

可能这个可以配置,可以配置的更大。

这是我的猜测。

    /**
     * Returns the value of this {@code Integer} as an
     * {@code int}.
     */
    public int intValue() {
        return value;
    }

拆箱就是直接返回类中的value就行了,比较简单;

练习题

    public static void main(String[] args) {
        Integer i1 = 40;
        Integer i2 = 40;
        Integer i3 = 0;
        Integer i4 = new Integer(40);
        Integer i5 = new Integer(40);
        Integer i6 = new Integer(0);

        System.out.println("i1=i2   " + (i1 == i2));//true
        System.out.println("i1=i2+i3   " + (i1 == i2 + i3));//true
        System.out.println("i1=i4   " + (i1 == i4));//false
        System.out.println("i4=i5   " + (i4 == i5));//false
        System.out.println("i4=i5+i6   " + (i4 == i5 + i6));//true  是因为有加好,就是运算了,运算的话,我们就会比较数值
        System.out.println("40=i5+i6   " + (40 == i5 + i6));//true


        Integer i7 = new Integer(115);
        Integer i8 = new Integer(40);
        Integer i9 = new Integer(155);
        System.out.println("155=i5+i6   " + (155 == i7 + i8));//true
        System.out.println("i9=i5+i6   " + (i9 == i7 + i8));//true
    }

如果有运算,那么比较的就是值,这个好好记住。

如果是new的 用== ,那么比较的是内存地址 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值