V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
hugedata
V2EX  ›  程序员

有感于 Java 中的 Integer,来一个题目。

  •  
  •   hugedata · 2018-07-20 11:15:12 +08:00 · 2711 次点击
    这是一个创建于 2079 天前的主题,其中的信息可能已经有所发展或是发生改变。
    有感于这个帖子:/t/472515
    来一个鬼畜版,先猜一猜程序输出结果,然后跑一把验证下看看:
    public static void main(String[] args) {
    try
    {
    fuck();
    }
    catch (NoSuchFieldException e)
    {
    e.printStackTrace();
    }
    catch (IllegalAccessException e)
    {
    e.printStackTrace();
    }

    for (Integer i = 1; i < 4; i++) {
    System.out.println(i);
    }
    }

    private static void fuck() throws NoSuchFieldException, IllegalAccessException {
    Integer x = 100;
    Class c = Integer.class.getDeclaredClasses()[0];
    Field f = c.getDeclaredField("cache");
    f.setAccessible(true);
    Integer[] cache = (Integer[]) f.get(x);
    cache[130] = cache[131];
    }
    8 条回复    2018-07-20 19:50:25 +08:00
    blindpirate
        1
    blindpirate  
       2018-07-20 11:25:16 +08:00   ❤️ 1
    老梗了,奇技淫巧
    specita
        2
    specita  
       2018-07-20 12:24:13 +08:00
    我理解的是,integer 做++操作的时候,如果在 cache 范围内,只是把数组下标加 1 咯...
    promise2mm
        3
    promise2mm  
       2018-07-20 12:50:31 +08:00   ❤️ 2
    看了一下 Integer 的 valueOf 源码:
    public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
    return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
    }

    --> 伪代码:
    if i in[-128, 127]
    return cache[i + 128];
    return new Integer(i);

    现在把 cache[130] -> cache[131];
    即当 for 循环到 2 的时候, 调用 valueOf(2) == 3
    直接跳过了 2.
    feiyuanqiu
        4
    feiyuanqiu  
       2018-07-20 13:03:02 +08:00 via Android
    原理楼上都说了,就说个题外话,知乎的轮子哥真是带坏了好多人 demo 代码的命名
    hugedata
        5
    hugedata  
    OP
       2018-07-20 13:34:01 +08:00
    @feiyuanqiu 知乎的轮子哥是谁?
    seancheer
        6
    seancheer  
       2018-07-20 14:20:17 +08:00
    @hugedata 指的是你那种 fuck,shit 之类的方法,变量命名方式。。。这个人在知乎回答某些编程问题时经常这么干。
    alamaya
        7
    alamaya  
       2018-07-20 14:58:34 +08:00
    你这一堆反射正常人不用翻源码都看出来有坑
    98jiang
        8
    98jiang  
       2018-07-20 19:50:25 +08:00
    就是把 2 换成 3 了吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2786 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 15:05 · PVG 23:05 · LAX 08:05 · JFK 11:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.