是连接一个空字符串做一个字符串转换真的那么糟吗? [英] Is concatenating with an empty string to do a string conversion really that bad?

查看:124
本文介绍了是连接一个空字符串做一个字符串转换真的那么糟吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个 char 变量,后来我想将它们连接成一个字符串。这是我怎么做的:

  char c1,c2; 
// ...

String s =+ c1 + c2;

我看过有人说,+ trick是丑陋等,你应该使用 String.valueOf Character.toString 。我喜欢这个结构,因为:




  • 我喜欢使用语言功能而不是API调用如果可能


    • 通常情况下,语言通常比API更稳定吗?

    • 如果语言特性只隐藏API调用,那么更有理由更喜欢它!


      • 更抽象!隐藏很好!



  • 我喜欢 c1 c2 在视觉上处于同一水平


    • String.valueOf(c1)+ c2 表明 c1

    valueOf 或 Character.toString 优先于+






    琐事:在 java.lang.AssertionError ,以下行出现7次,每个类型都不同:

      this(+ detailMessage); 


    解决方案

    这是Java语言中更具表达性的领域之一,+ 似乎已经根深蒂固。



    请参见字符串连接在JLS。

     + c1 + c2 
    >

    等同于

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


    b $ b

    ,除了所有的中间对象不是必要的(因此效率不是动机)。规范说,一个实现可以使用 StringBuffer 或不。由于这个特性是内置的语言,我没有理由使用更详细的形式,特别是在一个已经详细的语言。


    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);
    

    解决方案

    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.

    这篇关于是连接一个空字符串做一个字符串转换真的那么糟吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆