java - 这段代码中是否发生了装箱/拆箱?

标签 java boxing autoboxing

给定以下代码,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/

相关文章:

c# - 在 C# 中从列表到对象的装箱和拆箱

c# - 类型转换,拆箱,转换..?

java - 开发中如何避免在编译时浪费时间?

java - Spring Boot中如何获取系统属性值

java - 为什么迭代器仍然存在于java中

java - 我创建的类可以自动装箱吗?

java - 正确识别作为 varargs 参数传递的 int[]

java - Git 存储库的正确密码存储

c# - 当调用递归泛型接口(interface)上的扩展方法时,结构实例是否会被装箱?

java - 为什么 Java 自动装箱不扩展到自动装箱类型的方法的方法调用?