简体   繁体   English

我应该将Integer转换为int吗?

[英]Should I convert Integer to int?

I have read threads where the convertion of an Integer to an int is a must, BUT I encountered this thing. 我已经阅读过将Integer转换为int的线程,但是我遇到了这个问题。 My code was : 我的代码是:

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String numberOne = "12";

String numberTwo = "45";

Integer myint1 = Integer.valueOf(numberOne);

Integer myint2 = Integer.valueOf(numberTwo);

int sum = myint1.intValue() + myint2.intValue(); //line6

System.out.print(sum);

It gave me a warning of unnecessary unboxing at line6 and recommended me this instead: 它给了我一个关于第6行不必要拆箱的警告,并建议我这样做:

int sum = myint1 + myint2; //newline6

Both prints gave me the same result. 这两个版画给了我相同的结果。 Isn't it a must to convert Integer to int at line 6? 是不是必须在第6行将Integer转换为int?

The compiler will do the same unboxing automatically for you (since JDK 5), so 编译器会自动为你做同样的拆箱(从JDK 5开始),所以

int sum = myint1.intValue() + myint2.intValue();

is a bit redundant and 有点多余

int sum = myint1 + myint2;

will have the same behavior. 将有相同的行为。

That said, you can parse the String s directly into int s, and avoid both the boxing and the unboxing: 也就是说,您可以将String直接解析为int ,并避免装箱和取消装箱:

int myint1 = Integer.parseInt(numberOne);
int myint2 = Integer.parseInt(numberTwo);
int sum = myint1 + myint2;

It is unnecessary. 这是不必要的。

Accoring to jls , Integer will be auto unboxed to int when you put them besides + . 根据jls ,当你将它们放在+以外时, Integer将自动取消装箱到int

Numeric contexts apply to the operands of an arithmetic operator. 数字上下文适用于算术运算符的操作数。

Numeric contexts allow the use of: 数字上下文允许使用:

  • an unboxing conversion (§5.1.8) 拆箱转换(§5.1.8)

If you use Java 1.5 or higher you don't need to use Integer.intValue(), it's done by the compiler. 如果使用Java 1.5或更高版本,则不需要使用Integer.intValue(),它由编译器完成。 Source: How to convert Integer to int? Source: 如何将Integer转换为int?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM