java包装类(源码解析)

  1. java数据类型分为
    • 基础类型(primitive)
    • 引用类型(reference type)
  2. 包装类就是在基础类型上对应的引用类型
  • boolean、byte、int、double……
  • Boolean、Byte、Integer、Double……
    /**
     * The {@code Class} instance representing the primitive type
     * {@code int}.
     *
     * @since   JDK1.1
     */
    @SuppressWarnings("unchecked")
    public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");

源码中可以看出,包装类的实例是就是通过反射机制获取的基础类型的
3.区别

  • 基本类型只有值 包装类型是对象,值相同地址可以不同
    public class Main {
    public static void main(String[] args) {
        Integer s1=new  Integer(128);
        Integer s2=new  Integer(128);
        System.out.printf("%d%d\n",s1,s2);
        System.out.printf("%s\n",s1==s2?"相同":"不同");
        System.out.printf("%s\n",s1.equals(s2)?"相同":"不同");
        }
    }
    /*
    128128
    不同
    相同
    */
    
  • 包装类作为一个类必定有很多函数可以调用,比如toString()方法,使用更灵活;同时作为对象,它也可以是null
  1. 包装类创建方式
  • Integer s1=new Integer(128);
  • Integer s2=Integer.valueOf(127);Integer s3=127走的是valveOf

使用valueof方法,如果用的是-128-127,会使用Integer中的缓存。从而两个对象其实指向一个地址

public class Main {
    public static void main(String[] args) {
        Integer s1=Integer.valueOf(127);
        Integer s2=Integer.valueOf(127);
        System.out.printf("%s\n",s1==s2?"相同":"不同");
        System.out.printf("%s\n",s1.equals(s2)?"相同":"不同");
    }
}
/*
相同
相同
*/

缓存池部分的源码

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; //默认是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);//取用户给的值和默认127中的较大值
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);//防止超出int范围的最大值
                } 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() {}
    }
posted @ 2021-01-04 12:26  魏晋南北朝  阅读(110)  评论(0编辑  收藏  举报