public AbstractStringBuilder append(String str) {
if (str == null) str = "null"; //如果str==null 那么str=“null”
int len = str.length();
ensureCapacityInternal(count + len); //len是传入的字符串的长度,count是已经存在的字符的长度
str.getChars(0, len, value, count);
count += len;
return this;
}
private void ensureCapacityInternal(int minimumCapacity) { //ensureCapacityInternal(count + len);
确保传入的值大于 现在
// overflow-conscious code
if (minimumCapacity - value.length > 0) //value.length是容器的大小
expandCapacity(minimumCapacity);
}
void expandCapacity(int minimumCapacity) {
int newCapacity = value.length * 2 + 2;
if (newCapacity - minimumCapacity < 0)
newCapacity = minimumCapacity;
if (newCapacity < 0) {
if (minimumCapacity < 0) // overflow
throw new OutOfMemoryError();
newCapacity = Integer.MAX_VALUE;
}
value = Arrays.copyOf(value, newCapacity); //这个方法适用于扩容的,把旧的value放入新的长度为newCapacity 的char型数组中
}
str.getChars(0, len, value, count); //添加
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
if (srcBegin < 0) {
throw new StringIndexOutOfBoundsException(srcBegin);
}
if (srcEnd > value.length) {
throw new StringIndexOutOfBoundsException(srcEnd);
}
if (srcBegin > srcEnd) {
throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
}
System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
} 数组 0 数组 count len-0
//这个方法应该是把string,插入到数组
//因为数组是不能改变大小的,所以呢?所以啊,因该是又建立了一个更大的数组,然后将新的数据放在末尾
StringBuilder源码分析
Java字符串操作与内存管理
最新推荐文章于 2024-06-19 10:31:06 发布
本文深入探讨了Java中字符串拼接、字符获取与数组操作的优化策略,以及内部实现的内存分配机制,旨在提高开发者在处理字符串时的效率与理解。

731

被折叠的 条评论
为什么被折叠?



