Integer (number) to String
Here is my simple 开发者_JAVA百科question
We can convert integer, float, double
to String like String s = "" + i;
so why do we need String s = Integer.toString(i);
? just requirements of OO programmig ?
Thanks
Because "" + i
is a very bad practice. It converts to string by concatenating an empty string and an integer, which causes, internally, the creation of a StringBuilder
instance, the appending of the empty string, the call to Integer.toString()
, the appending of the conversion, and then the call to StringBuilder.toString()
.
Integer.toString()
does just what is needed : converting the integer to a string. It's thus much more efficient, and also much clearer and readable, because it tells what it does : converting an integer to a string.
String s = "" + i;
is just a shortcut. The compiler translates this to something like String s = "" + Integer.toString(i);
.
"integer" is a basic type, and the compiler can implicitly convert it.
"Integer" is an object type, and has its own method to provide the conversion.
In this site it makes a comparation of the 2 methods: http://en.literateprograms.org/Convert_Integer_to_String_(Java)
I don't have time to probe but it is the same if you only do this?: String text = i; I think only works with concatenation, but not in an assignment purely. String s = "" + i; is not so good looking...
The code
"" + i
is turned into
new StringBuilder().append(i).toString();
This creates three objects whereas
Integer.toString(i)
creates only 2. This makes the later more efficient and can save you about 0.1 microsecond per call.
However, simplicity of code is usually more important than performance and the time it takes you to write/check/maintain a longer sequence of code is usually worth more than the few cycles you might save.
e.g. say i
becomes a long type. In the first case, you would not need to change the code, it would still be.
""+i
however the second example would need to be changed, everywhere it is used, to
Long.toString(i);
A minor change, but one which is likely to have been completely unnecessary.
精彩评论