这两天在自学java,发现Java中StringBuffer类的setLength()方法有点奇怪,在此请教高手了!!!下面是一些源代码及运行结果:代码1:publicclasshello{publicstaticvoidmain(Stringar...
这两天在自学java,发现Java中StringBuffer类的setLength()方法有点奇怪,在此请教高手了!!!下面是一些源代码及运行结果:
代码1:
public class hello{
public static void main(String args[]){
StringBuffer str=new StringBuffer("hello world!");
System.out.println(str+" "+str.length()+" "+str.capacity());
str.setLength(10);//10小于str.length()=12
System.out.println(str+" "+str.length()+" "+str.capacity());
}
}
运行结果:
hello world! 12 28
hello worl 10 28
(ps:这个结果显而易见)
代码2:(ps:就是把str.setLength(10)中的10改为比str的length=12大的数13)
public class hello{
public static void main(String args[]){
StringBuffer str=new StringBuffer("hello world!");
System.out.println(str+" "+str.length()+" "+str.capacity());
str.setLength(13);//13大于str.length()=12
System.out.println(str+" "+str.length()+" "+str.capacity());
}
}
运行结果:
hello world! 12 28
hello world!
(ps:就是hello world!后面的输出内容都不能显示了,而且更奇怪的是,如果在上面代码中的最好一句后面添加输出语句,那么结果都显示不了)
代码3:(ps:就是在输出时,把str放到后面输出)
public class hello{
public static void main(String args[]){
StringBuffer str=new StringBuffer("hello world!");
System.out.println(str+" "+str.length()+" "+str.capacity());
str.setLength(13);//13大于str.length()=12
System.out.println(str.length()+" "+str.capacity()+" "+str);
}
}
运行结果:
hello world! 12 28
13 28 hello world!
(这结果又很正常)
是不是很奇怪?请高手们分析解决吧!!!
展开