如何编程实现 2 + 2 = 5?

忘我的追寻 2014-11-24 23:30:23 累计浏览 6,044 次

   Write a program that makes 2 + 2 = 5,看到这个题目,感觉很新颖,第一个答案就是用Java实现的。用上了Java中的整型实例池的概念。以前只看到过实例池导致两个对象的指针相同的问题,即

Integer a = new Integer(2);    Integer b = new Integer(2);    System.out.print(a == b);    

   上面的代码最终输出的是true,按照Java对象的申请原则来说,这里应该是false才对。正是因为JVM在实现的时候,默认生成了一些Integer对象的实例,当需要的实例是池子中已经存在的数值时,直接返回已经生成的对象的引用,不必新构造对象。这样可以极大减少实例数目和程序运行性能。

   而这个题目是将池子中的对象的内容进行了修改,最终使得取回的实例的值发生了改变。这样其实很危险的,如果在正式运行程序的业务代码之前,做这个修改,那么整个程序的运行逻辑将产生混乱。

import java.lang.reflect.Field;

   public class Main {

       public static void main(String[] args) throws Exception {

           Class cache = Integer.class.getDeclaredClasses()[0];

           Field c = cache.getDeclaredField("cache");

           c.setAccessible(true);

           Integer[] array = (Integer[]) c.get(cache);

           array[132] = array[133];

           System.out.printf("%d",2 + 2);

       }

   }

   上面是具体的代码,最终输出的结果为5,作者给出的解释为:

   You need to change it even deeper than you can typically access. Note that this is designed for Java 6 with no funky parameters passed in on the JVM that would otherwise change the IntegerCache.

   Deep within the Integer class is a Flyweight of Integers. This is an array of Integers from −128 to +127. cache[132] is the spot where 4 would normally be. Set it to 5.

   利用缓存的读写接口,将4这个实例的缓存对象的指针改为指向5的实例对象了,这样,当应用程序取出4时,实际上返回的是5的引用,打印出来的也就是5了。

同分类推荐文章

  1. 从 JetBrains 的亏损聊起 (2026-11-13 19:40:02)
  2. OpenLogi 上手:高性能低占用的支持多终端的本地无账号罗技驱动 (2026-11-13 17:40:02)
  3. 拿着锤子找钉子,AI 时代的创新幻觉 (2026-11-13 15:10:02)

查看更多 开发者 文章 →

建议继续学习

  1. SmartSprites - 命令行形式的CSS Sprites生成器 (累计阅读 124,345)
  2. Fix Bug的五个阶段 (累计阅读 43,262)
  3. Java开发岗位面试题归类汇总 (累计阅读 23,166)
  4. android 开发入门 (累计阅读 20,150)
  5. 我的PHP,Python和Ruby之路 (累计阅读 13,718)
  6. HashMap解决hash冲突的方法 (累计阅读 13,136)
  7. 如何成为一名黑客 (累计阅读 11,077)
  8. 做个懂产品的程序员 (累计阅读 10,017)
  9. 一个大二学生有关如何成为一名软件工程师的疑问及答复 (累计阅读 9,716)
  10. Java程序员应该知道的10个eclipse调试技巧 (累计阅读 8,362)