背景和问题

  在看别人整理的资料时,看到如下一段代码:

package com.sitech.test;/** * 自动装箱和拆箱 jdk1.6 * @author liaowp * */public class TestInteger {    public static void main(String[] args) {        Integer i1 = 80, i2 = 80, i3 = 999, i4 = 999;        System.out.println(i1 == i2);//true        System.out.println(i3 == i4);//false    }}

  如果没有看过源码的同学肯定觉的答案要么是2个true要么是2个false。我刚看到这一段代码的时候也觉的是2个true,感觉自己100%确定,不过真正运行之后才发现傻眼了,一个true一个false,这是Bug吧。其实LZ以前看过一部分Integer源码了,但是现在想想好像看的不认真,尴尬了。于是被这个问题触发了LZ要认真看一次Integer源码了(我要认真了,哈哈)。

  我们还是回到上面那个问题吧,先把问题解决了在吹nb。我们可以看到上面的代码4个变量都是Integer的引用,所以输出的==运算比较的不是Integer值而是Integer引用。装箱的本质是什么呢?当我们给一个Integer对象赋一个int值的时候,会调用Integer类的静态方法valueOf,我们看一看valueOf方法就知道为什么会有这样的结果了。

    /**     * 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) {//是一个静态方法 IntegerCache是一个内部类        assert IntegerCache.high >= 127;//断言  参考http://lavasoft.blog.51cto.com/62575/43735/        if (i >= IntegerCache.low && i <= IntegerCache.high)//如果i大于对于IntegerCache.low()且i小于等于IntegerCache.high            return IntegerCache.cache[i + (-IntegerCache.low)];//直接从缓存取出来        return new Integer(i);//新创建一个Integer对象    }

  从上面的代码中我们可以看出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 -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;//最小值是-128        static final int high;//最高        static final Integer cache[];//缓存数组  这三个都final,不可修改的        static {//静态代码块   静态代码块会比改造方法先执行            // high value may be configured by property            int h = 127;//默认的            String integerCacheHighPropValue =//定义一个String                 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");//取得设置的值            if (integerCacheHighPropValue != null) {//如果设置了就用设置的值                int i = parseInt(integerCacheHighPropValue);//把String转换为int                i = Math.max(i, 127);//获得i和127的更大的一个,其实是不能小与默认的                // Maximum array size is Integer.MAX_VALUE                h = Math.min(i, Integer.MAX_VALUE - (-low));//如果取的小的那个,不能超过Integer的最大值+low            }            high = h;//最大值为127

            cache = new Integer[(high - low) + 1];//创建缓存数组大小            int j = low;//最小值            for(int k = 0; k < cache.length; k++)                cache[k] = new Integer(j++);//缓存初始化        }        private IntegerCache() {}//私有构造    }

问题解决

Integer的缓存

  看完之后我相信基本都知道为啥一开始的那一段代码会这样了,我现在做一个小的总结,Integer里面有一个内部类IntegerCache,是用来做缓存优化性能的。默认缓存了-128到127中间的数字,据说这些使的比较频繁。其实java里面好多的类都有这样的优化。如果在-128-127之间的就直接拿缓存的,不在的就new一个Integer。所以这也就解释了上面的那个问题了嘛

转载于:https://blog.51cto.com/zhangtaoze/1917470

由自动装箱和拆箱引发我看Integer源码相关推荐

  1. 自动装箱与拆箱引发的享元设计模式

    2019独角兽企业重金招聘Python工程师标准>>> /*** 自动装箱与拆箱*/ public class Autoboxing {public static void main ...

  2. Integer自动装箱和拆箱,以及不使用不使用new关键字直接赋值会遇到的的问题

    Integer直接赋值使用==判断是否相等 //java中如果Integer不是new出Integer对象,而是直接赋值如Integer a=100;Integer b=100;System.out. ...

  3. 自动装箱,拆箱和NoSuchMethodError

    J2SE 5为Java编程语言引入了许多功能. 这些功能之一是自动装箱和拆箱 ,这是我几乎每天都没有考虑过的功能. 它通常很方便(尤其是与收藏夹一起使用时),但有时会导致一些令人讨厌的惊喜 ,即&qu ...

  4. 详解Java的自动装箱与拆箱(Autoboxing and unboxing)

    一.什么是自动装箱拆箱 很简单,下面两句代码就可以看到装箱和拆箱过程 //自动装箱 Integer total = 99;//自定拆箱 int totalprim = total; 简单一点说,装箱就 ...

  5. Java中的自动装箱和拆箱

    自动装箱和拆箱 自动装箱和拆箱 自动装箱: 拆箱 1. 为什么要有包装类(或封装类) 2. 基本数据类型与对应的包装类: 3. 类型间的转换 4. 何时发生自动装箱和拆箱 赋值.数值运算时 方法调用时 ...

  6. Java的知识点20——包装类基本知识、包装类的用途、自动装箱和拆箱、包装类的缓存问题

    包装类基本知识 将基本数据类型存储到Object[]数组或集合中的操作 包装类均位于java.lang包 "数字型"都是java.lang.Number的子类.Number类是抽象 ...

  7. Java自动拆装箱面试_跟王老师学泛型(二):Java自动装箱与拆箱

    Java 自动装箱与拆箱(Autoboxing and unboxing) 主讲教师:王少华 QQ群:483773664 学习目标: 掌握Java 基本数据对应的包装类 掌握Java 自动装箱与拆箱 ...

  8. Java13-day04【Integer、int和String的相转、自动装箱和拆箱、Date、SimpleDateFormat、Calendar、异常、try...catch、throws】

    视频+资料(工程源码.笔记)[链接:https://pan.baidu.com/s/1MdFNUADVSFf-lVw3SJRvtg   提取码:zjxs] Java基础--学习笔记(零起点打开java ...

  9. java-Integer的自动装箱与拆箱

    package com.day9.Wrapclass; public class Demo4Integer { /** * A:案例演示 * JDK5的新特性自动装箱和拆箱 * Integer ii ...

最新文章

  1. 月入5W,月花销不足2K的程序员,可免费获得AI女友一名
  2. Codeforces Round #337 (Div. 2) D. Vika and Segments 线段树扫描线
  3. italic与oblique的区别
  4. codeforce训练2总结
  5. 第三次软工作业——实现最大字段和算法并进行判定条件覆盖
  6. PostgreSQL 9.6 keepalived主从部署
  7. 干货:调度算法的价值与阿里的应用实践(内有赛事福利)
  8. python3的输出函数_教女朋友学Python3(二)简单的输入输出及内置函数查看 原创...
  9. poj1036GangstersDP
  10. Android listview局部刷新
  11. android根据经纬度获取位置,Android获取经纬度
  12. NYOJ 366 STL 全排列
  13. java输出中写html标签,java 输出html标签
  14. 摩托车闪光控制器专用芯片MST1172
  15. 2.格式化输出与输入
  16. 在橙黄色网站设计中寻找灵感
  17. Mac.zsh- no matches found- httpx[http2]
  18. 基于Java毕业设计学生选拔系统源码+系统+mysql+lw文档+部署软件
  19. python爬虫:爬取男生喜欢的图片
  20. idea配置xml约束问题

热门文章

  1. java的Access restriction错误
  2. 初学者如何开发出一个高质量的J2EE系统
  3. 漫谈WinCE输入法的编写(四)
  4. 计算机教授技术追踪劫匪,打脸 911警察
  5. js如何判断字符串里面是否含有某个字符串
  6. 《云计算:原理与范式》一3.9 SaaS集成服务
  7. 【笔记】与Android选项卡一周
  8. mysql-data-dumper
  9. Cygwin运行nutch报错:Failed to set permissions of path
  10. 应不应该使用inline-block代替float