MyStringBuilder
(新建一个模拟的MyStringBuild类实现StringBuild部分功能)
java中String类产生的对象是不可变的,任何对String对象的增删改都会引发新的String对象的生成,如果垃圾不能及时回收,就会造成内存被大量占用,所以java为此而提出了StringBuffer类,该类生成的对象是可变的,也就是说可以在原字符串基础上进行增删改,实质上StringBuffer是一个带有一定容量的字符数组,在它的容量范围内可以对其进行随意添加,一旦其自带容量不足,它就会进行自动扩容,它会新建一个新的字符数组用来存放添加原字符数组和新添加的字符串。所以String类的对象作为常量使用,如果要对其进行频繁的修改,我们会使用StringBuffer类的对象。那么为什么jdk1.5以后为什么又提出了一个StringBuilder类呢?这是因为StringBuffer要兼顾线程的同步,那么它的执行效率就会大大降低,所以java又提出了在单线程模式下能够高效运行的StringBuilder类。以下为自定义的StringBuilder类。
import java.util.Arrays;
public class MyStringBuilder {
//自带缓冲的字符数组
private char[] value;
//字符数组中实际存放字符的个数
private int count=0;
//自定义三个构造函数
public MyStringBuilder(){
value=new char[16];
}
public MyStringBuilder(int capacity){
value=new char[capacity];
}
public MyStringBuilder(String str){
value=new char[str.length()+16];
}
//得到字符数组中的字符个数
public int length(){
return count;
}
public int capacity(){
return value.length;
}
public MyStringBuilder append(String str){
int len=str.length();
ensureCapacity(count+len,len);//如果原字符容量不足,会自动扩展容量
str.getChars(0, len, value, count);
count+=len;
return this;
}
private void ensureCapacity(int capacity,int len) {
//数据超出容量
if(capacity-value.length<0){
int newCapacity=value.length+len+2;
value=Arrays.copyOf(value, newCapacity);
}
}
public String toString(){
return new String(value,0,count);
}
}
public class MyStringBuildTest {
public static void main(String[] args) {
MyStringBuilder msb=new MyStringBuilder();
msb.append("helloworld").append("hellojava").append("12345").append("helloworld");
System.out.println("总容量大小:"+msb.capacity());
System.out.println("字符串长度:"+msb.length());
System.out.println("字符串:"+msb.toString());
}
}