有时java让我困惑。 我有大量的int初始化要做。

真正的区别是什么?

Integer.toString(我) 新的整数(我).toString ()


当前回答

在这里 整数。toString调用Integer类中的静态方法。它不需要对象调用。

如果调用new Integer(i),首先创建一个Integer类型的实例,它是一个完整的Java对象,封装了int i的值。然后调用它的toString方法,要求它返回自己的字符串表示形式。

其他回答

另一个选项是静态字符串。返回对象的值的方法。

String.valueOf(i)

对我来说,它感觉比Integer.toString(i)更正确。当i的类型改变时,例如从int变为double,代码将保持正确。

虽然我喜欢fhucho的推荐

String.valueOf(i)

具有讽刺意味的是,这个方法实际上调用

Integer.toString(i)

因此,如果你喜欢它的读取方式并且不需要基数,可以使用String.valueOf(i),但也知道它比Integer.toString(i)效率低。

好:

Integer.valueOf(i).toString()

在这里 整数。toString调用Integer类中的静态方法。它不需要对象调用。

如果调用new Integer(i),首先创建一个Integer类型的实例,它是一个完整的Java对象,封装了int i的值。然后调用它的toString方法,要求它返回自己的字符串表示形式。

1. integer.tostring(我)

Integer i = new Integer(8);
    // returns a string representation of the specified integer with radix 8
 String retval = i.toString(516, 8);
System.out.println("Value = " + retval);

2.新整数(i)条toString()。

 int i = 506;

String str = new Integer(i).toString();
System.out.println(str + " : " + new Integer(i).toString().getClass());////506 : class java.lang.String