Java StringBuilder append() 和空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3960712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:38:05  来源:igfitidea点击:

StringBuilder append() and null values

javanullappendstringbuilder

提问by look4chirag

I have a list of Strings, and I want to concatenate them with spaces in between. So I'm using StringBuilder. Now if any of the Strings are null, they get stored in the StringBuilderliterally as 'null'. Here is a small program to illustrate the issue:

我有一个Strings列表,我想用它们之间的空格连接它们。所以我正在使用StringBuilder. 现在,如果Strings 中的任何一个是null,它们就会被存储在StringBuilder字面上作为“空”。下面是一个小程序来说明这个问题:

public static void main(String ss[]) {
    StringBuilder sb = new StringBuilder();

    String s;
    s = null;

    System.out.println(sb.append("Value: ").append(s));
}

I'd expect the output to be "Value: " but it comes out as "Value: null"

我希望输出为“Value:”但它显示为“Value:null”

Is there a way around this problem?

有没有办法解决这个问题?

采纳答案by Anthony

You can do a check on the object before appending it:

您可以在添加对象之前对其进行检查:

sb.append("Value: ");
if (s != null) sb.append(s);
System.out.println(sb);

A key point to make is that null is not the same an an empty String. An empty String is still a String object with associated methods and fields associated with it, where a null pointer is not an object at all.

要说明的一个关键点是 null 与空字符串不同。空字符串仍然是一个带有关联方法和字段的字符串对象,其中空指针根本不是对象。

From the documentation for StringBuilder's append method:

来自 StringBuilder 的 append 方法的文档:

The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument. If str is null, then the four characters "null" are appended.

String 参数的字符按顺序附加,通过参数的长度增加此序列的长度。如果 str 为空,则附加四个字符“空”。

回答by posdef

Null check as @Shynthriir has mentioned is the simplest most efficient way (AFAIK) to get around the problem.

@Shynthriir 提到的空检查是解决问题的最简单最有效的方法(AFAIK)。

I would however strongly recommend initiating strings to an empty string String str = "";instead, which would save you a lot of headache in a more complex programming effort.

但是,我强烈建议将字符串初始化为空字符串String str = "";,这样可以在更复杂的编程工作中为您省去很多麻烦。

回答by Jon Skeet

I'm not sure why you'd expect it to come out empty, given that the documentationis pretty clear:

鉴于文档非常清楚,我不确定为什么您希望它是空的:

If str is null, then the four characters "null" are appended.

如果 str 为空,则附加四个字符“空”。

Basically you need to either not call append at all if you have a null reference, or switch the value for "".

基本上,如果您有空引用,则根本不需要调用 append,或者切换“”的值。

You could write a method to do this substitution if you find yourself doing it a lot:

如果您发现自己经常这样做,您可以编写一个方法来执行此替换:

public static String nullToEmpty(String text) {
    return text == null ? "" : text;
}

Indeed, I've just looked at the Guavadocumentation and the Stringsclass has exactly that method (but with a parameter called stringinstead of text).

确实,我刚刚查看了Guava文档,并且Strings该类具有该方法(但使用一个名为string而不是 的参数text)。

回答by Sage Nadjafinia

You can use commons-lang's StringUtils#defaultString():

您可以使用 commons-lang 的StringUtils#defaultString()

sb.append("Value: ").append(StringUtils.defaultString(myVar));

回答by dokaspar

For my purpose, I needed to generalize Answer #2 a little bit. Here is the same function, taking Object as argument, instead of String:

出于我的目的,我需要稍微概括一下答案#2。这是相同的函数,将 Object 作为参数,而不是 String:

private String nullToEmpty(Object obj) {
    return obj == null ? "" : obj.toString();
}

回答by robert

In one line you can do:

在一行中,您可以执行以下操作:

System.out.println(sb.append("Value: ").append((s==null)?"":s));

回答by Chris Roberts

With Java 8 you could also use the java.util.Optionalclass to provide a default value:

在 Java 8 中,您还可以使用java.util.Optional类来提供默认值:

System.out.println(sb.append("Value: ").append(Optional.ofNullable(s).orElse("")));

System.out.println(sb.append("Value: ").append(Optional.ofNullable(s).orElse("")));

回答by Benas

import java.util.Objects;
...
sb.append(Objects.toString(s, ""));

Uses Java internal utils, no external libs are needed. toStringtakes String, checks if it is nulland if it is null, then returns specified default value, in this case ""(empty string), if it is not nullit returns provided string.

使用 Java 内部工具,不需要外部库。toString接受字符串,检查是否是null,如果是null,则返回指定的默认值,在这种情况下""(空字符串),如果不是,null则返回提供的字符串。