1700442702
1700442703
return this;
1700442704
1700442705
}
1700442706
1700442707
//字符数组,容纳的是新字符串的字符
1700442708
1700442709
char buf[]=new char[count+otherLen];
1700442710
1700442711
//取出原始字符串放到buf数组中
1700442712
1700442713
getChars(0,count, buf,0);
1700442714
1700442715
//追加的字符串转化成字符数组,添加到buf中
1700442716
1700442717
str.getChars(0,otherLen, buf, count);
1700442718
1700442719
//复制字符数组,产生一个新的字符串
1700442720
1700442721
return new String(0,count+otherLen, buf);
1700442722
1700442723
}
1700442724
1700442725
其整体看上去就是一个数组拷贝,虽然在内存中的处理都是原子性操作,速度非常快,不过,注意看最后的return语句,每次的concat操作都会新创建一个String对象,这就是concat速度慢下来的真正原因,它创建了5万个String对象呀!
1700442726
1700442727
(3)append方法拼接字符串
1700442728
1700442729
StringBuilder的append方法直接由父类AbstractStringBuilder实现,其代码如下:
1700442730
1700442731
public AbstractStringBuilder append(String str){
1700442732
1700442733
//如果是null值,则把null作为字符串处理
1700442734
1700442735
if(str==null)str=“null”;
1700442736
1700442737
int len=str.length();
1700442738
1700442739
//字符串长度为0,则返回自身
1700442740
1700442741
if(len==0)return this;
1700442742
1700442743
int newCount=count+len;
1700442744
1700442745
//追加后的字符数组长度是否超过当前值
1700442746
1700442747
if(newCount>value.length)
1700442748
1700442749
expandCapacity(newCount);//加长,并做数组拷贝
1700442750
1700442751
//字符串复制到目标数组
[
上一页 ]
[ :1.700442702e+09 ]
[
下一页 ]