java - NULL 对象的 StringBuffer 行为

标签 java null stringbuilder

当 NULL 对象附加到实例时,我无法理解 StringBuilder 的以下行为:

public class StringBufferTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String nullOb = null;
        StringBuilder lsb = new StringBuilder();

        lsb.append("Hello World");
        System.out.println("Length is: " + lsb.length());// Prints 11. Correct

        lsb.setLength(0);
        System.out.println("Before assigning null" + lsb.length());    
        lsb.append(nullOb);
        System.out.println("Length now is:" + lsb.length()); // Prints 4. ???
    }

}

最后的 print 语句不打印 0。谁能帮我理解这个行为?

最佳答案

来自 StringBuffer API -

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuffer.html#append(java.lang.String)

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.

这应该解释长度为 4。

关于java - NULL 对象的 StringBuffer 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8040967/

相关文章:

JAVAFX 列未填充字符串

java - servlet 以编程方式设置身份验证

mysql - 可空列的行为不一样

c - "Throw NULL"C 中的语句

asp.net - Web 控件与 StringBuilder

java - Hibernate 实体代理初始化

java - 计算mysql中的总登录注销时间

java - 在Java中,如何避免空白jtextfield输入?

c# - 使用 StringBuilder 重复字符串

java - 为什么Java中字符串连接比StringBuilder更快?