如何在Java中修改整数加法? [英] How to modify integer addition in java?

查看:74
本文介绍了如何在Java中修改整数加法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上我正在做一些研究,因为我很好奇它是否可以完成,我找到了这段代码:

So basically I was doing some research because I was curious to see if it could be done and I found this code:

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];

      int  n = 2+2;
      System.out.println(n);
      System.out.printf("%d",2 + 2);
    }
}

我只是很好奇为什么printf语句现在会返回5,但是打印整数n会给我4。

I was simply curious why the printf statement would now return 5, but printing integer n would sill give me 4.

推荐答案

Java缓存256 Integer 对象表示从-128到127之间的数字。当 int 被装箱到 Integer 时,如果其值介于-128和127,将使用缓存中的 Integer 对象。 (在此处了解详情)。语言如何做到这一点是实现细节。在您的Java版本中,它将此缓存存储在 Integer 的内部类中,在 Integer [] 字段中缓存。在其他Java版本中,这可能会更改,因此您的代码可能会中断。

Java caches 256 Integer objects representing the numbers from -128 to 127. When an int gets boxed to an Integer, if its value is between -128 and 127, the Integer object from the cache will be used. (Learn more here). How the language does this is implementation detail. In your version of Java, it stores this cache in an inner class in Integer, in an Integer[] field called cache. In some other version of Java, this might change, so your code might break.

代码的第一部分正在执行的操作是获取整数缓存,并将索引132设置为与索引133相同。由于此数组从-128开始,因此索引132将对应于4,而索引133将对应于5。这意味着您已将缓存中的4替换为5。

What the first part of your code is doing, is getting the integer cache, and setting index 132 to be the same as index 133. Since this array starts from -128, index 132 would correspond to where 4 is, and index 133 would be where 5 is. This means you have replaced 4 in the cache with a 5.

printf 2 +的参数2 ,首先被求值为4。然后将其装箱到 Integer 。这是因为 printf 仅接受 Object 作为其第二个参数。因为4在-128到127之间,所以使用了高速缓存,并访问了数组的索引132,因为如果没有,那么 Integer 4就应该在这里。 t修改了数组。但是您已经修改了数组,所以它得到了5个。

The argument to printf, 2 + 2, first gets evaluated to 4. Then it gets boxed to an Integer. This is because printf only accepts an Object as its second parameter. Because 4 is between -128 and 127, the cache is used, and index 132 of the array is accessed, because that's where the Integer 4 would have been, if you haven't modified the array. But you have modified the array, so it got 5 instead.

另一方面,由于<$ c, println 仍会打印4。 $ c> println 有一个接受 int 的重载,因此那里没有装箱。

On the other hand, println still prints 4 because println has an overload that accepts int, so no boxing occurs there.

方式,您不是在修改整数加法,而是在修改整数装箱。

By the way, you are not modifying "integer addition", you are just modifying "integer boxing".

这篇关于如何在Java中修改整数加法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆