我读过线程,其中必须将整数转换为整数,但我遇到了这个问题。我的代码是:
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 - 我应该将 Integer 转换为 int 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48974456/