让我们来看看这段代码:
package com;
public class StringTest2
{
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer();
String s = null;
sb.append(s);
System.out.println(sb.length());
StringBuilder sb2 = new StringBuilder();
sb2.append(s);
System.out.println(sb2.length());
}
}
结果会输出,有人一定会说输出0.
结果是什么呢?
怎么回事呢,明明添加了一个null值,结果竟然是4.
让我们来看看append方法的源码就知道了.
StringBuilder:
// Appends the specified string builder to this sequence.
private StringBuilder append(StringBuilder sb) {
if (sb == null)
return append("null");
int len = sb.length();
int newcount = count + len;
if (newcount > value.length)
expandCapacity(newcount);
sb.getChars(0, len, value, count);
count = newcount;
return this;
}
StringBuffer的append方法是在它的父类中实现的:
public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
int len = str.length();
if (len == 0) return this;
int newCount = count + len;
if (newCount > value.length)
expandCapacity(newCount);
str.getChars(0, len, value, count);
count = newCount;
return this;
}
这两个append方法都有共同的:
if (str == null) str = "null";
int len = str.length();
如果str 是 null,就賦予str = "null" 这个字符串,而再是
null了.
而"null"这个字符串的长度自然是4了.