当 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/