我有一个 String
列表,我想用它们之间的空格连接它们。所以我使用 StringBuilder
。现在,如果任何 String
为 null
,它们将按字面意思作为“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/