StringBuffer sb = new StringBuffer(2004);
sb.append("-");
sb.append(6);
sb.append("-");
sb.append(14);
System.out.println(sb);
你猜会输出什么?
"2004-6-14"
错了,输出的是"-6-14"
我们看到StringBuffer重载了append(),
看到append(int )的效果,
又看到new StringBuffer(String s)
等价与
{
?? StringBuffer sb = new StringBuffer();
?? sb.append(s);
}
就以为new StringBuffer(int n);
等价于:
{
?? StringBuffer sb = new StringBuffer();
?? sb.append(n);
}
其实不是.
new StringBuffer(int n);表示new一个StringBuffer,并且初始化它的长度到n,
它里面的内容还是空的.
看看文档的说明:
??? /**
???? * Constructs a string buffer with no characters in it and an
???? * initial capacity specified by the length argument.
???? *
???? * @param????? length?? the initial capacity.
???? * @exception? NegativeArraySizeException? if the length
???? *?????????????? argument is less than 0.
???? */
博客通过代码示例探讨了StringBuffer的使用。展示了使用`new StringBuffer(int n)`初始化及`append`方法的代码,指出`new StringBuffer(int n)`是初始化长度为n且内容为空,并非等价于`append(n)`,还给出了文档说明。

477

被折叠的 条评论
为什么被折叠?



