【学习笔记】自动封装拆箱

【学习笔记】自动封装拆箱


java的基本类型共有8种,由于基本类型的数据不是对象,有是有需要将数据作为对象使用,因此java为其提供了相应的包装类。

byte -> Byte
char -> Character
short -> Short
int -> Integer
long -> Long
float -> Float
double -> Double
boolean -> Boolean

装箱:基本类型数据转换成相对应的包装对象数据
拆箱:将引用类型数据转换为对应的基本类型数据

J2SE5.0提供了自动装箱拆箱,所以一般情况下不需要我们特别注意。
不过,有一些有趣的细节存在:

public static void main(String[] args) {
		Integer a = 127;
		Integer b = 127;
		Integer c = 128;
		Integer d = 128;
		
		System.out.println(a == b);//true
		System.out.println(a == 127);//true
		System.out.println(c == d);//false
		System.out.println(c == 128);//true
}

在java中,“==”和“!=”对于对象的比较是比较对象引用,而不是值
对于基本类型数据则是比较其值

其中第二跟第四行比较时,进行了自动拆箱,其本身等同于127==127,所以这里第二、第四是正确的

那么这里为什么a==b是对的,而c==d是错的呢

这是因为,在自动封箱时,java在编译时调用Integer.valueOf(num)将值封装,而在该方法中

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

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

简单的说,就是在IntegerCache中已经缓存了-128~127的Integer对象,在创建Integer对象时,如果是该范围内的,则直接从该缓存中返回对应对象,否则直接new一个Integer对象。
所以,对于a=b=127,其对于的是同一个对象,而c=d=128则是等同2个不同对象。

说到这,不得不再说另一个案例

public static void main(String[] args) {
		Integer a = new Integer(0);
		Integer b = new Integer(0);
		while(a >= b && a <= b && a != b){
			System.out.println("run");
		}
}

这是等同一个while(true)的死循环,因为当调用new Integer时,会直接生成一个对象,也就是说a与b是属于2个不同的对象,在这>=<=操作,都属于拆箱比较操作,所以该案例条件会成立。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值