【Java八大包装类】

包装类

为了更好的操作8大基本数据类型,使Java完全符合“万物皆对象”,为每一种基本数据类型设计了对应的包装类型:Byte、Short、Integer、Float、Double、Boolean、Character

装箱与拆箱

装箱:基本数据类型转换为对应的包装类型

拆箱:包装类型转换为对应的基本数据类型

在jdk1.5开始,Java采用自动拆箱、自动装箱

手动装箱、手动拆箱示例:

int num1=100;
        //手动装箱
        Integer integer1=new Integer(num1);
        System.out.println("包装Integer类型:"+integer1);
        //手动拆箱
        int splitInteger=integer1.intValue();
        System.out.println("基本int类型:"+splitInteger);

一、

数值类型的自动拆箱操作JVM会调用重写于Number抽象类的xxxValue()方法,Number是表示数字值类型的包装类可转换为基本数据类型平台类的超类,所有的数值类型的包装类都继承Number。单独对于Character、Boolean俩种非数值类型拆箱操作来自于自身类的xxxValue()方法

运用Debug测试如下代码则会得出该结论(需要注意在idea中debug时需要点击红色小箭头进入):

Integer i=100;
        int i2=i;

相关原码:

	//Character类中的方法
	public char charValue() {
        return value;
    }
    //Boolean类中的方法
    public boolean booleanValue() {
        return value;
    }
//Number抽象类原码
public abstract class Number implements java.io.Serializable {
	public abstract int intValue();
    public abstract long longValue();
    public abstract float floatValue();
    public abstract double doubleValue();
    public byte byteValue() {
        return (byte)intValue();
    }
    public short shortValue() {
        return (short)intValue();
    }
}

二、

自动装箱操作来自于对应包装类独有的valueOf方法

测试代码(使用Debug,需要注意在idea中debug时需要点击红色小箭头进入)

public static void main(String[] args) {
        Byte b=10;
        Short s=20;
        Integer i=100;
        Long l=200L;
        Float f=3.14f;
        Double d=13.14;
        Character c='a';
        Boolean flag=true;
    }

结论:以上测试代码在自动装箱时JVM都会执行到对应包装类的valueOf静态方法

相关原码:

(这里只是抽取出包装类对应的方法写在一起便于参考,不能误解为以下方法在同一个类中)

public static Byte valueOf(byte b) {
        final int offset = 128;
        return ByteCache.cache[(int)b + offset];
    }
    
public static Short valueOf(short s) {
        final int offset = 128;
        int sAsInt = s;
        if (sAsInt >= -128 && sAsInt <= 127) { // must cache
            return ShortCache.cache[sAsInt + offset];
        }
        return new Short(s);
    }

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

public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
    }

public static Float valueOf(float f) {
        return new Float(f);
    }

public static Double valueOf(double d) {
        return new Double(d);
    }

public static Character valueOf(char c) {
        if (c <= 127) { // must cache
            return CharacterCache.cache[(int)c];
        }
        return new Character(c);
    }

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

关于包装类使用==和equals方法比较的问题

==比较
基本数据类型与包装类时,会发生自动拆箱变成对应的基本数据类型比较;
如果两方都为包装类,则不会拆箱,JVM判断的是包装类对象的引用地址;
不同包装类型引用的 == 比较,会出现编译错误,不能比较。

equals比较
equals方法内比较的参数为基本数据类型,会先将参数自动装箱成对应的包装类;
equals方法内比较的参数为引用数据类型,会使用intanceof判断
该引用是否为当前包装类型的引用,如果判断为true会拆箱使用==比较,
如果判断该参数引用不为当前包装类的引用直接返回false。
由于程序中需要使用的基本数据类型值基本在一个小范围之内,假
设这个小范围的值全需要用到其包装类型,这个时候就会创建包装类对象进行自动装箱。
会出现基本数据类型值相同的
包装类对象很多很多,浪费了不少内存。为了提高程序效率,包装类使用了一个缓存的思想,
在除Float、Double的其他包装类中,将各基本数据类型定义一个小范围的缓存。
如果定义的包装类型的值(Integer i=100 这种赋值方式)在这个范围,直接引用,不用new空间了。
Boolean的缓存没有缓存内部类,而是定义了为俩个常量:TRUE、FALSE

拿 Integer 缓存示例:
Integer 内部定义了 IntegerCache内部类,IntegerCache中定义了Integer[] 
保存了从 -128~127 范围的整数,使用自动装箱的方式,
给Integer赋值(Integer i=100 这种赋值方式)的范围在 -128~127范围内时,
可以直接使用数组中的元素,就不用 new 了,从而提高效率。

各包装类特有缓存功能的内部类原码,由原码很直观的知道缓存的范围(这里只是写在一起便于参考,不能误解为以下内部类在同一个类中):

private static class ByteCache {
        private ByteCache(){}

        static final Byte cache[] = new Byte[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Byte((byte)(i - 128));
        }
    }

private static class ShortCache {
        private ShortCache(){}

        static final Short cache[] = new Short[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Short((short)(i - 128));
        }
    }

private static class LongCache {
        private LongCache(){}

        static final Long cache[] = new Long[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Long(i - 128);
        }
    }

private static class CharacterCache {
        private CharacterCache(){}

        static final Character cache[] = new Character[127 + 1];

        static {
            for (int i = 0; i < cache.length; i++)
                cache[i] = new Character((char)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() {}
    }

验证代码(使用Debug更直观,需要注意在idea中debug时需要点击红色小箭头进入):

        Integer i1=100;
        Integer i2=100;
        System.out.println(i1==i2);//true
        int i3=100;
        System.out.println(i3==i2);//true

        Integer i4=128;
        Integer i5=128;
        System.out.println(i4==i5);//false
        int i6=128;
        System.out.println(i6==i5);//true
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南风知我意唔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值