Java基础 (3) 包装类

2019-02-18  本文已影响0人  perry_Fan

思考原生与包装类型的区别。
装箱就是自动将基本数据类型转换为包装器类型;拆箱就是自动将包装器类型转换为基本数据类型。

Integer i = 10;  //装箱
int n = i;   //拆箱

在装箱的时候自动调用的是Integer的valueOf(int)方法。
而在拆箱的时候自动调用的是Integer的intValue方法。

public static Integer valueOf(int i) {
        if(i >= -128 && i <= IntegerCache.high)
            return IntegerCache.cache[i + 128];
        else
            return new Integer(i);
}

private static class IntegerCache {
        static final int high;
        static final Integer cache[];

        static {                                         // 静态代码块  
            final int low = -128;

            // high value may be configured by property
            int h = 127;
            if (integerCacheHighPropValue != null) {
                // Use Long.decode here to avoid invoking methods that
                // require Integer's autoboxing cache to be initialized
                int i = Long.decode(integerCacheHighPropValue).intValue();
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - -low);
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;

            for(int k = 0; k < cache.length; k++)                      // 初始化  
                cache[k] = new Integer(j++);
        }

        private IntegerCache() {}
}

在装箱时,valueOf方法会被自动调用:如果整型字面值在[-128,127]之间,便返回 IntegerCache.cache(在类加载时就自动创建) 中已经存在的对象的引用;否则,创建一个新的Integer对象并返回。

当使用“==”运算符在基本类型和其包装类对象之间比较时,涉及到自动装箱、拆箱机制,遵循如下规则:

  1. 只要两个操作数中有一个是基本类型或表达式(即包含算术运算符),就是比较它们的数值是否相等。
  2. 否则,就是判断这两个对象的内存地址是否相等,即是否是同一个对象。

引用链接:https://blog.csdn.net/justloveyou_/article/details/52651211

上一篇 下一篇

猜你喜欢

热点阅读