我正在做一个项目,从int到String的所有转换都是这样完成的:

int i = 5;
String strI = "" + i;

我不熟悉Java。

这是惯例吗,还是像我猜想的那样,出了什么问题?


当前回答

很多大学入门课程似乎都在教授这种风格,有两个原因(根据我的经验):

它不需要理解类或方法。通常,在提到“类”这个词之前就已经教过了——甚至方法调用也没有。所以使用String.valueOf(…)这样的东西会让学生感到困惑。 这是“操作符重载”的一个例子——事实上,这是作为惯用重载操作符卖给我们的(这没什么奇怪的,因为Java不允许自定义操作符重载)。

因此,它可能是出于教学的需要(尽管我认为这只是糟糕的教学),也可能是用来说明一个很难在Java中演示的原则。

其他回答

有多种转换为字符串的方法:

StringBuilder string = string.append(i).toString();
String string = String.valueOf(i);
String string = Integer.toString(i);

Mostly ditto on SimonJ. I really dislike the ""+i idiom. If you say String.valueOf(i), Java converts the integer to a string and returns the result. If you say ""+i, Java creates a StringBuilder object, appends an empty string to it, converts the integer to a string, appends this to the StringBuilder, then converts the StringBuilder to a String. That's a lot of extra steps. I suppose if you do it once in a big program, it's no big deal. But if you're doing this all the time, you're making the computer do a bunch of extra work and creating all these extra objects that then have to be cleaned up. I don't want to get fanatic about micro-optimization, but I don't want to be pointlessly wasteful either.

十多年前,我在一门本科水平的java入门课程中教授了这种技术。但是,我应该指出,IIRC,我们还没有接触到String和Integer类方法。

这种技术很简单,打字也很快。如果我所做的只是打印一些东西,我将使用它(例如,System.out。Println ("" + i);。然而,我认为这不是进行转换的最佳方式,因为当它以这种方式使用时,需要考虑一下才能意识到发生了什么。此外,如果性能是一个问题,它似乎更慢(下文以及其他答案)。

就我个人而言,我更喜欢Integer.toString(),因为它很明显会发生什么。String.valueOf()将是我的第二选择,因为它似乎令人困惑(看看darioo回答后的评论)。

我写了一些类来测试这三种技术:"" + I,整数。toString和String.ValueOf。每个测试只是将整数从1到10000转换为字符串。然后,我分别用Linux time命令运行了五次。Integer.toString()比String.valueOf()稍微快一次,他们捆绑了三次,String.valueOf()更快一次;然而,这种差异从来没有超过几毫秒。

“”+ i技术在每个测试中都比这两者都慢,除了一个测试,它比Integer.toString()快1毫秒,比String.valueOf()慢1毫秒(显然是在同一个测试中,String.valueOf()比Integer.toString()快)。虽然它通常只慢了几毫秒,但有一个测试慢了大约50毫秒。YMMV。

我知道的另一种方法来自Integer类:

Integer.toString(int n);
Integer.toString(int n, int radix);

一个具体的例子(尽管我认为你不需要):

String five = Integer.toString(5); // returns "5"

它也适用于其他基本类型,例如Double.toString。

请看这里了解更多细节。

将整数转换为字符串的方法有很多:

1)

Integer.toString(10);

2)

 String hundred = String.valueOf(100); // You can pass an int constant
 int ten = 10;
 String ten = String.valueOf(ten)

3)

String thousand = "" + 1000; // String concatenation

4)

String million = String.format("%d", 1000000)