我正在做一个项目,从int到String的所有转换都是这样完成的:
int i = 5;
String strI = "" + i;
我不熟悉Java。
这是惯例吗,还是像我猜想的那样,出了什么问题?
我正在做一个项目,从int到String的所有转换都是这样完成的:
int i = 5;
String strI = "" + i;
我不熟悉Java。
这是惯例吗,还是像我猜想的那样,出了什么问题?
当前回答
表达式
"" + i
导致I在运行时的字符串转换。表达式的整体类型是String。i首先转换为一个Integer对象(new Integer(i)),然后是String。valueOf(Object obj)被调用。所以它等于
"" + String.valueOf(new Integer(i));
显然,这比直接调用String的性能稍差。valueOf(new Integer(i)),这将产生完全相同的结果。
“”+i的优点是打字更容易/更快,有些人可能会认为,它更容易阅读。这不是一种代码气味,因为它并不表明有任何更深层次的问题。
(参考:JLS 15.8.1)
其他回答
表达式
"" + i
导致I在运行时的字符串转换。表达式的整体类型是String。i首先转换为一个Integer对象(new Integer(i)),然后是String。valueOf(Object obj)被调用。所以它等于
"" + String.valueOf(new Integer(i));
显然,这比直接调用String的性能稍差。valueOf(new Integer(i)),这将产生完全相同的结果。
“”+i的优点是打字更容易/更快,有些人可能会认为,它更容易阅读。这不是一种代码气味,因为它并不表明有任何更深层次的问题。
(参考:JLS 15.8.1)
这取决于你想如何使用你的String。这可以帮助:
String total = Integer.toString(123) + Double.toString(456.789);
很多大学入门课程似乎都在教授这种风格,有两个原因(根据我的经验):
它不需要理解类或方法。通常,在提到“类”这个词之前就已经教过了——甚至方法调用也没有。所以使用String.valueOf(…)这样的东西会让学生感到困惑。 这是“操作符重载”的一个例子——事实上,这是作为惯用重载操作符卖给我们的(这没什么奇怪的,因为Java不允许自定义操作符重载)。
因此,它可能是出于教学的需要(尽管我认为这只是糟糕的教学),也可能是用来说明一个很难在Java中演示的原则。
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.
有三种转换为字符串的方法
字符串字符串= "" + i; String String = String. valueof (i); String String = Integer.toString(i);