Integer (number) per line

Here is my simple question

We can convert integer, float, doubleto String as String s = "" + i;, therefore , why do we need String s = Integer.toString(i);? just OO programig requirements?

thank

+3
source share
5 answers

Because it "" + iis a very bad practice. It is converted to a string by combining an empty string and an integer, which calls inside, instantiating StringBuilder, adding an empty string, calling Integer.toString(), adding a transform, and then calling StringBuilder.toString().

Integer.toString()performs only what is needed: converting the integer to a string. This is much more efficient, as well as much clearer and more understandable, because it tells you what it is doing: converting the whole to a string.

+6

String s = "" + i; - . - String s = "" + Integer.toString(i);.

+1

"integer" , .

" " - .

0

: http://en.literateprograms.org/Convert_Integer_to_String_(Java)

, , ?:    = i; , , .   String s = "" + i; ...

0

"" + i

new StringBuilder().append(i).toString(); 

,

Integer.toString(i)

2. 0,1 .

However, simplicity of the code is usually more important than performance, and the time it takes to write / verify / maintain a longer sequence of code usually costs more than a few loops that you could save.

eg. for example, iit becomes long. In the first case, you will not need to change the code, it will still be.

""+i

however, the second example should be changed wherever it is used to

Long.toString(i);

A small change, but which would probably be completely unnecessary.

0
source

All Articles