AI全套:Python3+TensorFlow打造人脸识别智能小程序
最新人工智能资料-Google工程师亲授 Tensorflow-入门到进阶
黑马头条项目 - Java Springboot2.0(视频、资料、代码和讲义)14天完整版
Integer a = 1000, b = 1000;
System.out.println(a == b);//1
Integer c = 100, d = 100;
System.out.println(c == d);//2false
true基本知识:我们知道,如果两个引用指向同一个对象,用 == 表示它们是相等的。如果两个引用指向不同的对象,用 == 表示它们是不相等的,即使它们的内容相同。
这就是它有趣的地方了。如果你看去看 Integer.java 类,你会发现有一个内部私有类,IntegerCache.java,它缓存了从 - 128 到 127 之间的所有的整数对象。
所以事情就成了,所有的小整数在内部缓存,然后当我们声明类似——
Integer c = 100;
的时候,它实际上在内部做的是:
Integer i = Integer.valueOf(100);
/**
* 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) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}注释的大致意思是
所以…当定义的值在-128到127之间时, 使用的是同一个对象. 所以 c==d的结果为 true
Integer c = 100, d = 100;
System.out.println(c == d); // true同样的 Long, Short 中也有缓存cache. 值也是 -128~127
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
通过反射 API 你可能会误用此功能
运行下面的代码,享受它的魅力吧
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Class cache = Integer.class.getDeclaredClasses()[0];
Field myCache = cache.getDeclaredField("cache");
myCache.setAccessible(true);
Integer[] newCache = (Integer[]) myCache.get(cache);
newCache[132] = newCache[133];
int a = 2;
int b = a + a;
System.out.printf("%d + %d = %d", a, a, b); // 2 + 2 = 5 ?
}作者:明天丶你好_3f99
链接:https://www.jianshu.com/p/95b7b4b3af20
全栈架构社区交流群
「全栈架构社区」建立了读者架构师交流群,大家可以添加小编微信进行加群。欢迎有想法、乐于分享的朋友们一起交流学习。
看完本文有收获?请转发分享给更多人
往期资源: