Integer的valueOf方法

先上几个例子:

1         Integer it1 = 140;
2         Integer it2 = 140;
3         System.out.println(it1 == it2);

输出false。

1         Integer it1 = 100;
2         Integer it2 = 100;
3         System.out.println(it1 == it2);

输出true。

很奇怪的是为什么一个是true一个是false。

对这段代码反编译之后的结果如下:

1     Integer it1 = Integer.valueOf(100);
2     Integer it2 = Integer.valueOf(100);
3     System.out.println(it1 == it2);

从这段代码中可以看出Integer it1 = 100调用了Integer的valueOf方法,再来看看valueOf方法的源码:

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

从这段代码中可以看出,Integer内部维护了一个缓存数组cache,而这个缓存数组里缓存的是值的范围是:

-128到127。

所以在这个范围内的数字调用valueOf方法返回的都是同一个对象。

原文地址:https://www.cnblogs.com/huashui/p/3234792.html