StringBuilder

StringBuilder

1.不可继承


public final class StringBuilder extends AbstractStringBuilder
implements java.io.Serializable, CharSequence


2.内容可变



/**
* The value is used for character storage.
*/
char value[];



3.构造方法

默认构造一个长度为16的char数组




public StringBuilder(int capacity) {
super(capacity);
}

public StringBuilder() {
super(16);
}

public StringBuilder(String str) {
super(str.length() + 16);
append(str);
}




abstract class AbstractStringBuilder implements Appendable, CharSequence {
/**
* The value is used for character storage.
*/
char value[];

/**
* The count is the number of characters used.
*/
int count;

/**
* This no-arg constructor is necessary for serialization of subclasses.
*/
AbstractStringBuilder() {
}

/**
* Creates an AbstractStringBuilder of the specified capacity.
*/
// 构建一个长度为X的char类型数组
AbstractStringBuilder(int capacity) {
value = new char[capacity];
}
}



4.append()



public StringBuilder append(String str) {
super.append(str);
return this;
}






public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
int len = str.length();
if (len == 0) return this;
int newCount = count + len;
if (newCount > value.length)
expandCapacity(newCount);
str.getChars(0, len, value, count);
count = newCount;
return this;
}

// 数组拷贝,改变str的内容
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
if (srcBegin < 0) {
throw new StringIndexOutOfBoundsException(srcBegin);
}
if (srcEnd > count) {
throw new StringIndexOutOfBoundsException(srcEnd);
}
if (srcBegin > srcEnd) {
throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
}
System.arraycopy(value, offset + srcBegin, dst, dstBegin,
srcEnd - srcBegin);
}

// 添加新的字符串后的长度大于已有的容量,扩容处理,产生新的对象
// 扩容的长度,(leng+1)*2
void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2;
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {
newCapacity = minimumCapacity;
}
value = Arrays.copyOf(value, newCapacity);
}



其他:

1.str = str + str1 ; 或 str+= str1 ;
实质等价于 StringBuilder sb = new StringBuilder(str);sb.append(str1);

但在循环中使用 s+=s1 ;相当于每次都创建一个新的对象;

所以,多次进行字符串拼接操作时改为使用StringBuidler
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值