java - StringBuilder append() 和空值

标签 java null append stringbuilder

我有一个 String 列表,我想用它们之间的空格连接它们。所以我使用 StringBuilder。现在,如果任何 Stringnull,它们将按字面意思作为“null”存储在 StringBuilder 中。下面是一个小程序来说明这个问题:

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

    String s;
    s = null;

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

我希望输出为“Value:”,但输出为“Value:null”

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

最佳答案

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

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

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

来自 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.

关于java - StringBuilder append() 和空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3960712/

相关文章:

c++ - 将指向类的指针 append 到 QList QList<Class* >

python - 正确 append

java - 想要使用嵌入式凭据访问 Google Cloud Datastore

javascript - 验证表单时出现 "null or not an object"错误

MySQL Not Null 命令没有执行任何操作

android - 尝试在空对象引用上调用接口(interface)方法 'android.IInAppBillingService...

javascript - 使用 jQuery 添加/删除 <li> 元素

java - 环境变量不起作用

java - 正在接收另一个对象的输出,这是错误的

Java:关键字 "this"和Serialization