java 减去两个 Integer 对象会产生一个 Integer 还是一个原始 int?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7958282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:11:32  来源:igfitidea点击:

Does subtracting two Integer objects result in an Integer or a primitive int?

javawrapper

提问by aps

Say we have two Integer objects:

假设我们有两个 Integer 对象:

Integer i=100,j=200;

Does (j-i)evaluate to another Integer Wrapper object with value 100, or a primitive int?

是否(j-i)评估另一个值为 100 的 Integer Wrapper 对象,或一个原始类型int

回答by Sean Adkinson

Quick test shows that java is using an Integer cache, and re-uses the i:

快速测试表明 java 正在使用整数缓存,并重新使用i

@Test
public void test() {
    Integer i=100, j=200;
    System.out.println("i: " + System.identityHashCode(i));
    System.out.println("j: " + System.identityHashCode(j));

    Integer sub = j-i;
    System.out.println("j-i: " + System.identityHashCode(sub));
}

Outputs:

输出:

i: 1494824825
j: 109647522
j-i: 1494824825 <-- same as i

回答by Bhesh Gurung

The result will be an int100.

结果将是int100。

Both iand jwill be auto-unboxed so the result of i-jwill be an int.

双方ij会自动拆箱这样的结果i-j将是一个int

But if you assign the result to as follows:

但是,如果您将结果分配如下:

Integer r = i - j;

then the result will be auto-boxed again.

然后结果将再次自动装箱。