我是靠谱客的博主 执着雪碧,这篇文章主要介绍Interger的陷阱和源码解析,现在分享给大家,希望可以做个参考。

首先看下下面一个简单的程序会输出什么结果?

复制代码
1
2
3
4
5
6
7
8
9
10
11
public class IntegerTest { public static void main(String[] args) { Integer a = 123; Integer b = 123; Integer c = 128; Integer d = 128; System.out.println(a==b); System.out.println(c==d); } }

答案如下,是不是出乎意料:

复制代码
1
2
3
true false

我们知道==比较的是对象的引用,那么这里为什么会出现这种情况呢?

原理
首先这是JDK1.5版本开始添加的新特性,把-128~127常用的数字给缓存起来了,用于提升性能和节省内存开销,所以这个范围内的自动装箱(相当于调用valueOf(int i)方法)的数字都会从缓存中去获取,返回同一个数字,也就是从缓存中获取的自存地址也是一样的。所以在-128-127之前的值比较返回的true,而不在这个范围内的值不是从缓存中获取的,自然内存地址是不一样的,故返回false。

而我们通过new Integer(1) 这样就不会从缓存中获取了:

复制代码
1
2
3
4
5
6
7
8
Integer a1 = new Integer(123); Integer b1 = new Integer(123); Integer c1 = new Integer(128); Integer d1 = new Integer(128); System.out.println(a1==b1); System.out.println(c1==d1);

结果如下:

复制代码
1
2
3
false false

我们来翻下jdk中Integer的源码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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() {} }

这段IntegerCache的源码,把-128~high放在了缓存中:

复制代码
1
2
3
4
5
6
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }

这段valueOf的源码,先从缓存中获取,不在缓存范围内,则new Integer这样处理的。

从源码我们可以看到最小边界是-128,最大边界可以通过java.lang.Integer.IntegerCache.high去配置,但是也不会大于Integer.MAX_VALUE的最大值。

最后

以上就是执着雪碧最近收集整理的关于Interger的陷阱和源码解析的全部内容,更多相关Interger内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(72)

评论列表共有 0 条评论

立即
投稿
返回
顶部