[Java] 整型和字符串类型相互转换

1. String -> Integer

两种方法:

Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);

There is a slight difference between these methods:

  • valueOf returns a new or cached instance of java.lang.Integer
  • parseInt returns primitive int.

The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.

2. Integer -> String

三种方法:

String.valueOf(number) (my preference)
// or
"" + number (I don't know how the compiler handles it, perhaps it is as efficient as the above)
// or
Integer.toString(number)

[1] https://stackoverflow.com/questions/5585779/how-do-i-convert-a-string-to-an-int-in-java
[2] https://stackoverflow.com/questions/5071040/java-convert-integer-to-string

猜你喜欢

转载自blog.csdn.net/ftell/article/details/81216395