Java数据类型与封装类(从头开始,后续更新)

基本数据类型:

byte,short,char,int,long,boolean,double,float

封装类:

Byte,Short,Character,Integer,Long,Boolean,Double,Float

封装类和基本数据类型区别:

1.两者转换过程名称叫做,“拆箱”(intValue())、“装箱”(valueOf(int i))
2.基本数据类型只可以被运算,封装类具有基本数据类型不具有的操作,toString()等等

题目:请输出下面的值并验证

Integer a = 500;
Integer b = 500;
System.out.println(a == b);
System.out.println(a.equals(b));
Integer c = 100;
Integer d = 100;
System.out.println(c == d);
System.out.println(c.equals(d));
Integer e = 127;
Integer f = new Integer(127);
System.out.println(e == f);
Integer h = 128;
int i = 128;
System.out.println(h == i);

验证结果:
在这里插入图片描述

答案解析:
1.为什么第一个结果和第三个结果不同,这里需要查看一下Integer封装类中自动装箱的源码:

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

其实在初始化之前,Integer类内部就已经完成了一个缓存区的数据存储,有利于内存节省和效率.内部类中已经完成了从-128到127的数值的缓存,只要是装箱时是这些数值就可以直接用缓存区中现成的,不需要再新new一个了。所以第三次中两个Integer对象的地址都是指向同一个。

2.为什么最后一个是对的?
Integer h = 128;
int i = 128;
System.out.println(h == i);
这里当封装类和基本数据类型进行对比的时候,封装类就会自动拆箱(intValue(){return value;}),最后进行的是基本数据的比较。

上面问题Double,float类型的不行:在某个区间内,整数可以是有限个,但是浮点数是无线个的,所以每次装箱都是新new一个对象.其余类型都和Integer相似。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值