您的位置 首页 java

详解拆箱与装箱,用int、Integer举例从概念到代码层面

一、简介

在JAVA中,数据类型主要分为2大类,基本类型和引用类型。

基本类型大小以及包装类型对应关系

二、代码实例讲解

1、从int与Integer看

Integer的 valueOf(int i) 方法可以将一个基本数据类型转化为对应的包装类型,即装箱方法。

而Integer的 intValue() 方法则可以将一个包装类型转化为对应的基本数据类型,即拆箱方法。

 public void box01(){
        //自动装箱,底层其实执行了Integer a=Integer.valueOf(1);
        Integer a = 1;
        //自动拆箱,底层其实执行了int b=a.intValue();
        int b = a;

        /**
         *  public static Integer valueOf(int i) {
         *         if (i >= Integer cache .low && i <= IntegerCache.high)
         *             return IntegerCache.cache[i + (-IntegerCache.low)];
         *         return new Integer(i);
         *     }
         * 从源码中可看到valueOf 在缓存范围内会从缓存中拿,也就是常量池
         */  // 装箱
        Integer c = Integer.valueOf(11);
// 拆箱
        int d = c.intValue();

    }  

2、进一步理解装箱

装箱: 利用Integer的构造方法Integer(int value),即Integer c=new Integer(1);

自动装箱: 或者叫隐式装箱,直接给Integer赋值,即Integer d=1,在编译的时候,会调用Integer.valueOf()方法完成装箱。

三、从面试谈

  public static void box02(){
     Integer a = 100;
     Integer b = 100;
     Integer c = 200;
     Integer d = 200;
     System.out.println(a == b);
     System.out.println(c == d);

}  

输出结构:

输出结构

可以看出Integer类型的200 != 200;

看一下装箱的valueOf(int i)的源码:

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

从源码中能够看到 [-128,127] 是在cache区域中的,他们之间的“==”是返回true的。

Byte Short 、Integer、 Long 、Character的valueOf()实现机制类似。

其中相同值的Byte比较永远返回true,因为byte取值范围就是[-128,127]。

Short、Integer、Long的valueOf()基本一样,cache的范围都需要在[-128,127]。

Character中cache的范围只要小于等于127即可,因为char最小值为0,本来就大于等于-128。

但是Float、Double中的valueOf(),永远返回新创建的对象,因为一个范围内的整数是有限的,但是小数却是无限的,无法保存在缓存中。

Boolean 中只有两个对象,要么是true的Boolean,要么是false的Boolean,只要boolean的值相同,Boolean就相等。

关注我,每天推送技术文章。

文章来源:智云一二三科技

文章标题:详解拆箱与装箱,用int、Integer举例从概念到代码层面

文章地址:https://www.zhihuclub.com/200418.shtml

关于作者: 智云科技

热门文章

网站地图