public class Test{
public static void main(String[] args){
StringBuffer buf = new StringBuffer("Hard ");
String aString = "Waxworks";
buf.append(aString , 3 , 4);
int test = buf.capacity();
System.out.println(buf);
System.out.println(test);
}
}1、上面这段代码应该很容易看懂,问题在于buf.append(aString , 3 , 4);这条代码,书上和doc里都说第后一个参数是指
第一个索引后要追加的数量,但是当这段代码编译后,出现的结果是"Hard w"而不是我们想要的"Hard work"不知道是什么原因
2、还有个问题,这里的容量为什么仍就保持21??而添加进去的字符却没有增加它的容量??
public static void main(String[] args){
StringBuffer buf = new StringBuffer("Hard ");
String aString = "Waxworks";
buf.append(aString , 3 , 4);
int test = buf.capacity();
System.out.println(buf);
System.out.println(test);
}
}1、上面这段代码应该很容易看懂,问题在于buf.append(aString , 3 , 4);这条代码,书上和doc里都说第后一个参数是指
第一个索引后要追加的数量,但是当这段代码编译后,出现的结果是"Hard w"而不是我们想要的"Hard work"不知道是什么原因
2、还有个问题,这里的容量为什么仍就保持21??而添加进去的字符却没有增加它的容量??
这个buf.append(aString , 3 , 7);能得到你要的结果
这个你要看它的源代码和API
特别是这个方法
public AbstractStringBuilder append(CharSequence s, int start, int end) {
if (s == null)
s = "null";
if ((start < 0) || (end < 0) || (start > end) || (end > s.length()))
throw new IndexOutOfBoundsException(
"start " + start + ", end " + end + ", s.length() "
+ s.length());
int len = end - start;
if (len == 0)
return this;
int newCount = count + len;
if (newCount > value.length)
expandCapacity(newCount);
for (int i=start; i<end; i++)
value[count++] = s.charAt(i);
count = newCount;
return this;
}
int start,
int end)将指定 CharSequence 的子序列追加到此序列。
按顺序追加参数 s 中的字符,即从索引 start 开始到索引 end 结束的此序列的内容。此序列增加的长度为 end - start。 假设此字符序列的长度在执行 append 方法前为 n。如果 k 小于 n,则新字符序列中索引 k 处的字符等于原序列中索引 k 处的字符;否则它等于参数 s 中索引 k+start-n 处的字符。 如果 s 为 null,则认为 s 参数包含 4 个字符 "null",并以此为根据追加字符。
指定者:
接口 Appendable 中的 append
参数:
s - 要追加的序列。
start - 要追加的子序列的起始索引。
end - 要追加的子序列的结束索引。
返回:
此对象的一个引用。
抛出:
IndexOutOfBoundsException 如果 start 或 end 为负;或者 start 大于 end;或者 end 大于 s.length()
从以下版本开始:
1.5
String aString = "Waxworks";
char[] cr = aString.toCharArray();
buf.append(cr, 3, 4);
int test = buf.capacity();
System.out.println(buf);
System.out.println(test);
}}第2个问题我也不清楚。