通过Java代码可以实现1+1=3,先看代码
package com.shendd.test;
import java.lang.reflect.Field;
public class IntegerTest {
public static void main(String[] args) {
changeCache();
int a = 1;
System.out.printf("%d + %d = %d", a, a, a + a);
}
private static void changeCache() {
try {
Class<?> cache = Integer.class.getDeclaredClasses()[0];
Field myCache = cache.getDeclaredField("cache");
myCache.setAccessible(true);
Integer[] newCache = (Integer[]) myCache.get(cache);
newCache[130] = newCache[131];
} catch (Exception e) {
e.printStackTrace();
}
}
}
就是上面这段代码可以输出:1+1=3,不相信的同学可以亲自验证一下,如果不对,笔者愿终身搬砖,从此不再踏入IT界半步。
那么问题来了为什么1+1=3了呢?且听笔者详细道来...
在看一段代码:
Integer a = 127, b = 127;
Integer a1 = 128, b1 = 128;
System.out.println(a == b);
System.out.println(a1 == b1);
相信这段代码大家都会认为很简单,但是答案却不一样,有人会说输出true true,有人会说输出false false,然而,结果却是true false。为什么呢?
基本知识:==比较的是对象是否相等,如果两个引用指向同一个对象则==比较为true,否者为false,即使他们的内容相同。也就是说,上面的代码a和b指向的是同一对象,
a1和b1不是同一个对象,这是为什么呢?在看一段代码:
/**
* Returns a <tt>Integer</tt> instance representing the specified
* <tt>int</tt> value.
* If a new <tt>Integer</tt> 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.
*
* @param i an <code>int</code> value.
* @return a <tt>Integer</tt> instance representing <tt>i</tt>.
* @since 1.5
*/
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
这是Integer类的valueOf源码,由以上这段代码可以看出,当int值在-128到127之间的情况下,Integer直接返回IntegerCache类中存的值,该类是一个内部的私有类,它缓存了
-128到127之间所有的整数对象。所以问题就清晰了:Integer a = 127的时候,a存的就是IntegerCache类中返回来的内存中的地址,而Integer a1 = 128的时候,a1存的则是在
内存中新开辟的一个空间地址。也就是说如果值得范围在-128到127之间,它就从高速缓存返回实例。
现在你应该就知道为什么1+1=3了吧?