作者:jason christ
链接:https://www.zhihu.com/question/37760140/answer/74523291
来源:知乎
著作权归作者所有,转载请联系作者获得授权。

想起了1+1=3的那个
代码大概是这个样子…
—————————————-

public static void main(String[] args) throws Exception {
		Class integer = Integer.class.getDeclaredClasses()[0];
		Field field = integer.getDeclaredField("cache");
		field.setAccessible(true);
		Integer[] array =  (Integer[]) field.get(integer);
		array[130] = array[131];
		System.out.printf("%d", 1 + 1);
}

———————————————————————————————-
解解释一下,前面几步是反射就不说了,java里面有一个int常量池,也就是field.get(integer);这句代码所拿到的,它的长度是256,里面存着[-128-127]之间的数字.这个有什么用?看了下面的代码你就会理解了

                Integer a = -128;
		Integer b = -128;
		Integer c = -129;
		Integer d = -129;
		System.out.println(a == b);
//true
		System.out.println(c == d);//false

然后,System.out.printf这个方法并没有做验证,而是如果值在这个范围就直接从池中拿出来.
也就是说,如果我这样写

                for (int i = 0; i < array.length; i++) {
			array[i] = 12450;
		}
		for (int i = -128; i <= 127; i++) {
			System.out.printf("%d\n", i);
		}

输出的将都会是12450.
println就不会用这个问题,因为它用的是String.valueOf(i).

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

required