Java 将 int 传递给以 Integer 作为参数的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24655779/
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-08-14 13:51:04  来源:igfitidea点击:

Passing int to a method taking Integer as parameter?

java

提问by Varun

Is it Ok to pass int to a method which is taking Integer as parameter. Here is the code

将 int 传递给将 Integer 作为参数的方法是否可以。这是代码

public class PassingInt 
{
    public static void main(String args[])
    {
        int a = -1;
        passIntToInteger(a);//Is this Ok?
    }

    private static void passIntToInteger(Integer a) 
    {
        System.out.println(a);
    }

}

采纳答案by peter.petrov

Yes, it is OK, it will be auto-boxed.

是的,没关系,它会自动装箱。

The reverse is also OK and is called auto unboxing.

反过来也可以,称为自动拆箱。

More info here:

更多信息在这里:

Autoboxing and Unboxing

自动装箱和拆箱

回答by Christian

Yes, it is.

是的。

Why?Because of auto-boxing. Primitives are converted to an object of its corresponding wrapper class. From Java Tutorials:

为什么?因为自动装箱。原语被转换为其相应包装类的对象。来自Java 教程

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on.

自动装箱是 Java 编译器在原始类型与其对应的对象包装类之间进行的自动转换。例如,将 int 转换为 Integer,将 double 转换为 Double,等等。

In your case:

在你的情况下:

primitive type: int -> wrapper class: Integer

回答by Elliott Frisch

Yes, in your example it would be autoboxed(converted from an intprimitive to an Integerobject) -

是的,在您的示例中,它将被自动装箱(从int原语转换为Integer对象)-

public static void main(String args[]) {
    int a = -1;
    passIntToInteger(a); // <-- Auto Boxing
}

private static void passIntToInteger(Integer a) {
    System.out.println(a);
}

Java also has (auto-)unboxing (converting from an Integerobject to an intprimitive) -

Java 还具有(自动)拆箱功能(从Integer对象转换为int原语)-

public static void main(String args[]) {
    Integer a = -1;
    passIntegerToInt(a); // <-- Auto Un-Boxing
}

private static void passIntegerToInt(int a) {
    System.out.println(a);
}

This allows you to use primitives with collections, otherwise List<Integer>could not store int(s) (for example).

这允许您将原语与集合一起使用,否则List<Integer>无法存储int(例如)。

回答by FrancescoDS

Yes it is possible to do it, and it is possible to do also the opposite (from Integer to int)

是的,可以这样做,也可以做相反的事情(从整数到整数)