Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

java - Is concatenating with an empty string to do a string conversion really that bad?

Let's say I have two char variables, and later on I want to concatenate them into a string. This is how I would do it:

char c1, c2;
// ...

String s = "" + c1 + c2;

I've seen people who say that the "" + "trick" is "ugly", etc, and that you should use String.valueOf or Character.toString instead. I prefer this construct because:

  • I prefer using language feature instead of API call if possible
    • In general, isn't the language usually more stable than the API?
    • If language feature only hides API call, then even stronger reason to prefer it!
      • More abstract! Hiding is good!
  • I like that the c1 and c2 are visually on the same level
    • String.valueOf(c1) + c2 suggests something is special about c1
  • It's shorter.

Is there really a good argument why String.valueOf or Character.toString is preferrable to "" +?


Trivia: in java.lang.AssertionError, the following line appears 7 times, each with a different type:

    this("" + detailMessage);
question from:https://stackoverflow.com/questions/2506474/is-concatenating-with-an-empty-string-to-do-a-string-conversion-really-that-bad

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your arguments are good; this is one of the more expressive areas of the Java language, and the "" + idiom seems well entrenched, as you discovered.

See String concatenation in the JLS. An expression like

"" + c1 + c2

is equivalent to

new StringBuffer().append(new Character(c1).toString())
                  .append(new Character(c2).toString()).toString()

except that all of the intermediate objects are not necessary (so efficiency is not a motive). The spec says that an implementation can use the StringBuffer or not. Since this feature is built into the language, I see no reason to use the more verbose form, especially in an already verbose language.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...