本文翻译自:Java int to String - Integer.toString(i) vs new Integer(i).toString()
Sometimes java puzzles me. 有时java困惑我。
I have a huge amount of int initializations to make. 我有大量的int初始化。
What's the real difference? 真正的区别是什么?
-
Integer.toString(i)
-
new Integer(i).toString()
#1楼
参考:https://stackoom.com/question/GUQU/Java-int-to-String-Integer-toString-i-vs-new-Integer-i-toString
#2楼
I also highly recommend using 我也强烈推荐使用
int integer = 42;
String string = integer + "";
Simple and effective. 简单有效。
#3楼
更好:
Integer.valueOf(i).toString()
#4楼
Another option is the static String.valueOf
method. 另一个选项是静态String.valueOf
方法。
String.valueOf(i)
It feels slightly more right than Integer.toString(i)
to me. 感觉比Integer.toString(i)
对我更正确。 When the type of i changes, for example from int
to double
, the code will stay correct. 当i的类型改变时,例如从int
变为double
,代码将保持正确。
#5楼
Here Integer.toString
calls the static method in the class Integer. 这里Integer.toString
调用Integer类中的静态方法。 It does not require the object to call. 它不需要对象调用。
If you call new Integer(i)
you first create an instance of type Integer, which is a full Java object encapsulating the value of your int i. 如果调用new Integer(i)
,首先要创建一个Integer类型的实例,它是一个封装int i值的完整Java对象。 Then you call the toString
method on it to ask it to return a string representation of itself. 然后在其上调用toString
方法,要求它返回自身的字符串表示。
#6楼
Although I like fhucho's recommendation of 虽然我喜欢fhucho的推荐
String.valueOf(i)
The irony is that this method actually calls 具有讽刺意味的是,这种方法实际上是召唤
Integer.toString(i)
Thus, use String.valueOf(i)
if you like how it reads and you don't need radix, but also knowing that it is less efficient than Integer.toString(i)
. 因此,如果您喜欢它的读取方式并且不需要基数,请使用String.valueOf(i)
,但也要知道它的效率低于Integer.toString(i)
。