如何使用Integer IntegerCache

发布时间:2021-10-13 14:37:01 作者:iii
来源:亿速云 阅读:127

这篇文章主要介绍“如何使用Integer IntegerCache”,在日常操作中,相信很多人在如何使用Integer IntegerCache问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何使用Integer IntegerCache”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

 Integer s = 1;
 Integer s1 = 1;;
 System.out.println(s == s1);

 Integer s2 = 128;
 Integer s3 = 128;
 System.out.println(s2 == s3);

问题由此展开,会打印出true, false; 第二个是我们正常理解的答案。再理解为什么第一个打印是true,先了解下 == 和 equals

== :

基本类型一般都用 == ,比较的是内存地址,如果内存地址是一样的那么两个值自然也是相等的。

equals:

对象的比较一般都用equals, equals比较的是对象的内容

所以

Integer s = 1;
Integer s1 = 1;;
System.out.println(s.equals(s1)); // true

我们再回来看看开头的问题,关键在于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() {}
    }

-128 - 127范围的数字都放在了cache数组中,所以再找个范围内 == 比较都是true.

那么好处是直接在缓存中去取肯定要比生成一个对象要好太多啊

Byte Short Long 这几个都有类似的做法

到此,关于“如何使用Integer IntegerCache”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. 由自动装箱和拆箱引发我看Integer源码
  2. java中int和Integer有什么不同

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

上一篇:如何解决Could not find or load main class org.apache.spark.deploy.yarn.ApplicationMaster问题

下一篇:如何实现xp、2003开3389+非net创建管理用户+Shift后门+自删除的vbs脚本

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》