【问题标题】:String concatenation and + operator [duplicate]字符串连接和 + 运算符 [重复]
【发布时间】:2015-01-11 13:08:09
【问题描述】:

我正在尝试字符串连接和字符串上的 '+' 运算符并遇到以下问题 -

String xyz = "Hello" + null;
System.out.println("xyz= " +xyz);
String abc= "Hello".concat(null);
System.out.println("abc= " +abc); 

第一个输出是:Hellonull
第二个的输出是 空指针异常

我不明白为什么会有两个不同的输出。

【问题讨论】:

    标签: java string


    【解决方案1】:

    当您通过+ 运算符连接null 时,它始终会转换为“null”字符串。这解释了第一个输出 Hellonull。

    concat 函数内部如下所示:

    public String concat(String s) {
    
        int i = s.length();
        if (i == 0) {
            return this;
        } else {
            char ac[] = new char[count + i];
            getChars(0, count, ac, 0);
            s.getChars(0, i, ac, count);
            return new String(0, count + i, ac);
        }
    }
    

    来源:String concatenation: concat() vs "+" operator

    如您所见,它调用 s.length(),在您的情况下表示 null.length();这会导致您的 String abc= "Hello".concat(null); 语句出现 NullPointerException。

    编辑:我刚刚反编译了我自己的 String.concat(String s) 函数,它的实现看起来有点不同,但 NullPointerException 的原因保持不变。

    【讨论】:

      【解决方案2】:

      来自Docs

      If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
      
      Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.
      

      【讨论】:

        【解决方案3】:

        "Hello" + null 返回与"Hello".concat(String.valueOf(null)) 相同的结果。

        String.valueOf(null) 返回字符串“null”。

        【讨论】:

          【解决方案4】:
          /**
           * Concatenates this string and the specified string.
           *
           * @param string
           *            the string to concatenate
           * @return a new string which is the concatenation of this string and the
           *         specified string.
           */
          public String concat(String string) {
              if (string.count > 0 && count > 0) {
                  char[] buffer = new char[count + string.count];
                  System.arraycopy(value, offset, buffer, 0, count);
                  System.arraycopy(string.value, string.offset, buffer, count, string.count);
                  return new String(0, buffer.length, buffer);
              }
              return count == 0 ? string : this;
          }
          

          源代码中contact函数的第一行调用了null的count。所以会抛出空指针异常。

          【讨论】:

            【解决方案5】:

            在空引用上调用 concat() 会产生 NPE,因此“+”运算符将空引用视为“空”会产生不同的结果。

            【讨论】:

              猜你喜欢
              • 2012-11-11
              • 1970-01-01
              • 2021-12-10
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-11-10
              • 2014-02-27
              • 1970-01-01
              相关资源
              最近更新 更多