JAVA基础

基本数据类型 基本数据类型的包装类的缓存机制

Java语言有8种基本数据类型

  • 整型 byte short int long
  • 浮点型 float double
  • 字符型 char
  • 布尔类型 boolean

在这里插入图片描述

Java包装类的缓存机制

​ java 包装类的缓存机制,是Java 5中引入的一个有助于节省内存、提高性能的功能,只有在自动装箱时有效

  1. Integer包装类

    Integer a = 100; Integer b = 100;
    System.out.println(a == b);
    true
    

    包装类的自动装箱,起始底层实现是调用封装类的valueOf方法,

    Integer a =100; 相当于 Integer a = Integer.valueOf(100);

    Integer中的ValueOf():

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

    如果传入的参数 i >=IntegerCache.low或者<=IntegerCache.high,就从IntegerCache中获取对象

    Integer中IntegerCache的源码:

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

    JAVA官方的描述是:缓存以支持JLS要求的-128到127(含)之间的值的自动装箱的对象标识语义。首次使用时会初始化缓存。高速缓存的大小可以由-XX:AutoBoxCacheMax = 选项控制。在VM初始化期间,可以在sun.misc.VM类的私有系统属性中设置并保存java.lang.Integer.IntegerCache.high属性。

    默认范围为:-128到127之间,范围的最大值可以通过java.lang.Integer.IntegerCache.high设置,通过for循环将范围内的数据实例化为Integer对象放到cache数组里

    Integer a = 128;Integer b = 128; System.out.println(a == b); false
    

    输出结果为false,所以如果没有指定cache最大值时,在-128到127之间使用自动装箱时,会使用缓存

  2. Byte包装类

    	Byte a = 127;
        Byte b = 127;
        System.out.println(a == b); true
    

    Byte范围在**-128到127**,所以Byte的valueOf都是从ByteCache缓存中获取的

    public static Byte valueOf(byte b) {
        final int offset = 128;
        return ByteCache.cache[(int)b + offset];
    }
    

    Byte包装类中的ByteCache:

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

    与Integer不同的是,Byte不可以指定最大值,最大值始终是127

  3. Short包装类

    Short中的valueOf():

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

    Short中的ShortCache:

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

    与Byte一样,Short的最大范围也是不可以修改的,是-128~127

  4. Long包装类

    public static Long valueOf(String s) throws NumberFormatException
    {
        return Long.valueOf(parseLong(s, 10));
    }
    

    Long中的LongCache

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

    ​ Long的valueOf方法和LongCache类与Short包装类的实现一致,范围也是只能在-128 ~ 127之间

    5.Character包装类

    Character的valueOf():

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

    Character中的CharacterCache:

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

    Character的缓存范围在0 ~ 127之间

  5. Boolean包装类

    valueOf方法:

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

    true跟false都是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);
    
  6. Float包装类 & Double包装类

    valueOf方法:

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

    但不同的是,Float和Double没有使用缓存,直接new的对象

    java的包装类中:Byte,Short,Integer,Long,Character

    这些包装类都是使用static代码块进行初始化缓存,

    其中Integer的最大值可以通过java.lang.Integer.IntegerCache.high设置

    Boolean使用static final实例化的对象

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值