初学匿名内部类,求救
CharSequence cs =new CharSequence(){
public int length(){
return 10;
}
public char charAt(int index){
return 'A';
}
public CharSequence subSequence(int start,int end){
return null;
}
};
StringBuilder s = new StringBuilder(cs);
System.out.println(s);
内部类实现这个接口,最后结果是AAAAAAAAAA,有没有人能告诉我是怎么实现的啊!
------解决方案--------------------你的问题比较纠结。我想你的问题在看过StringBuilder的实现代码之后应当就好理解了,如下是最终生成StringBuilder内容的代码。
public AbstractStringBuilder append(CharSequence s, int start, int end) {
if (s == null)
s = "null";
if ((start < 0)
------解决方案-------------------- (start > end)
------解决方案-------------------- (end > s.length()))
throw new
IndexOutOfBoundsException(
"start " + start + ", end " + end + ", s.length() "
+ s.length());
int len = end - start;
ensureCapacityInternal(count + len);
for (int i = start, j = count; i < end; i++, j++)--注意这里
value[j] = s.charAt(i);--注意看这里
count += len;
return this;
}