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

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

我不熟悉Java。

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


当前回答

这不仅仅是优化。我不喜欢

"" + i

因为它没有表达出我真正想做的事情。

我不想将一个整数附加到一个(空)字符串。我想把一个整数转换成字符串:

Integer.toString(i)

或者,不是我的首选,但仍然比串联更好,获得一个对象的字符串表示(整数):

String.valueOf(i)

1. 对于经常调用的代码,比如在循环中,优化当然也是不使用串联的一个原因。

2. 这对于在System.out中使用真正的连接是无效的。println("Index: " + i);or String id = " id " + i;

其他回答

尝试简单的类型转换

char c = (char) i;

使用Integer.toString (tmpInt) .trim ();

有三种转换为字符串的方法

字符串字符串= "" + i; 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.

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

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