new StringBuffer(int n)的陷阱

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

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.

???? */

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航