千家信息网

如何使用Integer IntegerCache

发表于:2025-11-11 作者:千家信息网编辑
千家信息网最后更新 2025年11月11日,这篇文章主要介绍"如何使用Integer IntegerCache",在日常操作中,相信很多人在如何使用Integer IntegerCache问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作
千家信息网最后更新 2025年11月11日如何使用Integer IntegerCache

这篇文章主要介绍"如何使用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"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

0