[英]Should I convert Integer to int?
我已经阅读过将Integer转换为int的线程,但是我遇到了这个问题。 我的代码是:
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);
它给了我一个关于第6行不必要拆箱的警告,并建议我这样做:
int sum = myint1 + myint2; //newline6
这两个版画给了我相同的结果。 是不是必须在第6行将Integer转换为int?
编译器会自动为你做同样的拆箱(从JDK 5开始),所以
int sum = myint1.intValue() + myint2.intValue();
有点多余
int sum = myint1 + myint2;
将有相同的行为。
也就是说,您可以将String
直接解析为int
,并避免装箱和取消装箱:
int myint1 = Integer.parseInt(numberOne);
int myint2 = Integer.parseInt(numberTwo);
int sum = myint1 + myint2;
如果使用Java 1.5或更高版本,则不需要使用Integer.intValue(),它由编译器完成。 Source: 如何将Integer转换为int?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.