zoukankan      html  css  js  c++  java
  • Java自动装箱与拆箱以及常量池

    1.基本类型对应的包装类

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

    2. 自动拆箱与自动装箱

    自动装箱: 将基本数据类型自动转换成对应的包装类。
    本质上是通过包装类的valueOf()方法来实现的。

    自动拆箱:将包装类自动转换成对应的基本数据类型。
    本质上是通过包装类对象的xxxValue()来实现的。

    Integer i = 1; //自动装箱
    //Integer i = Integer.valueOf(1); 
    
    int k = i;//自动拆箱
    //int k = i.intValue(); 
    

    3.自动拆装箱的场景

    • 基本类型与包装类型进行大小比较,四则运算,条件运算符
    • 集合类使用时,只接受对象,会自动装箱

    3.例子

    public static void main(String[] args) {
            Integer i1 = new Integer(100);
            Integer j1 = new Integer(100);
            System.out.println(i1==j1);	//false
    
            Integer i2 = new Integer(100);
            int j2 = 100;
            System.out.println(i2==j2);	//true
    
            Integer i3 = new Integer(100);	//heap
            Integer j3 = 100;			//constant pool
            System.out.println(i3==j3);	//false
    
            Integer i4 = 127;
            Integer j4 = 127;
            System.out.println(i4==j4);	//true
    
            Integer i5 = 128;
            Integer j5 = 128;
            System.out.println(i5==j5); //false
        }
    
    • new Integer(100)每次都会创建一个新对象,而对于引用类型来说==比较的是引用地址,所以不相等。
    • java在编译Integer i = 100时,本质上调用Integer i = Integer.valueof(100),由下面java 8中对ValueOf()的定义以及IntegerCache()可知,valueof()创建的对象指向方法区。
    • 整型常量池中的常量范围:-128到127,所以在自动装箱时,把int变成Integer的时候,当你的int的值在-128到127时,返回的不是new出来的Integer对象,而是已经缓存在堆中的Integer对象。
    /**
         * Cache to support the object identity semantics of autoboxing for values between
         * -128 and 127 (inclusive) as required by JLS.
         *
         * The cache is initialized on first usage.  The size of the cache
         * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
         * 可以通过参数指定
         * During VM initialization, java.lang.Integer.IntegerCache.high property
         * may be set and saved in the private system properties in the
         * sun.misc.VM 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];//实例化cache缓存
                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;//断言必须大于127
            }
            private IntegerCache() {}
        }
    
        /**
         * Returns an {@code Integer} instance representing the specified
         * {@code int} value.  If a new {@code Integer} instance is not
         * required, this method should generally be used in preference to
         * the constructor {@link #Integer(int)}, as this method is likely
         * to yield significantly better space and time performance by
         * caching frequently requested values.
         *
         * This method will always cache values in the range -128 to 127,
         * inclusive, and may cache other values outside of this range.
         *
         * @param  i an {@code int} value.
         * @return an {@code Integer} instance representing {@code i}.
         * @since  1.5
         */
        public static Integer valueOf(int i) {
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];//引用地址相同
            return new Integer(i);
        }
    

    IntegerCache.cache内部实现了一个Integer的静态常量数组,在类加载的时候,执行static静态块进行初始化-128和127之间的Integer对象,存放到cache数组中。cache属于常量,存放在Java的方法区中。

    4.常量池

    java中基本类型的包装类的大部分都实现了常量池技术,要用于减少创建对象的数量,以减少内存占用和提高性能。如Byte,Short,Integer,Long,Character,Boolean;两种浮点数类型的包装类Float,Double并没有实现常量池技术。

  • 相关阅读:
    SerializationUtility
    ExtendHelper
    AutoTransformHandler
    Parameter Config
    Tools Function
    谈谈对C#中反射的一些理解和认识(上)
    WPF程序中App.Config文件的读与写
    WPF实现Windows资源管理器(附源码)
    安装VC++2015运行库时出现0x80240037错误
    对C#调用C++的dll的一点思考
  • 原文地址:https://www.cnblogs.com/innndown/p/12392210.html
Copyright © 2011-2022 走看看