我正在做一个项目,从int到String的所有转换都是这样完成的:
int i = 5;
String strI = "" + i;
我不熟悉Java。
这是惯例吗,还是像我猜想的那样,出了什么问题?
我正在做一个项目,从int到String的所有转换都是这样完成的:
int i = 5;
String strI = "" + i;
我不熟悉Java。
这是惯例吗,还是像我猜想的那样,出了什么问题?
当前回答
String strI = String.valueOf(i);
String string = Integer.toString(i);
两种方法都是正确的。
其他回答
尝试简单的类型转换
char c = (char) 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.
String strI = String.valueOf(i);
String string = Integer.toString(i);
两种方法都是正确的。
将整数转换为字符串的方法有很多:
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)
就我个人而言,我没有看到这段代码有什么不好的地方。
当您想记录一个int值,而记录器只接受一个字符串时,它非常有用。我想说,当你需要调用一个接受String的方法,但你有一个int值时,这样的转换是很方便的。
至于整数之间的选择。toString或String。这完全是个人品味的问题。 ...内部是字符串。valueOf调用Integer。顺便说一下toString方法。:)