给定以下代码,Java 编译器是否在这种情况下应用任何装箱/拆箱?
public static Integer sum(Iterable<Integer> numbers){
Integer sum = 0;
for(Integer n : numbers){
sum += n;
}
return sum;
}
最佳答案
是的,在使用 +
运算符执行加法时,Integer
对象会转换为 int
文字。看看这个link 。它说如下:
Because the remainder (%) and unary plus (+=) operators do not apply to Integer objects, you may wonder why the Java compiler compiles the method without issuing any errors. The compiler does not generate an error because it invokes the intValue method to convert an Integer to an int at runtime.
关于java - 这段代码中是否发生了装箱/拆箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55040193/