Top
首页 > 老文章 > 正文

new StringBuffer(int n)的陷阱

new StringBuffer(int n)的陷阱

new StringBuffer(int n)的陷阱
发布时间:2006-03-10 06:07        来源:        作者:

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.
???? */

加载更多

专题访谈

合作站点
stat