String StringBuffer StringBuilder原理

StringBuffer 和StringBuilder 节省内存的原理,在于拼接字符串的时候本身的对象不变,一直在变的是数组对象,通过不断的复制生成新的数组对象,达到拼接字符串,而StringBuffer和StringBuilder的代码逻辑一模一样,只是StringBuffer所有的方法都加了cynchronized,所以是线程安全的,可以自己写一个StringBuilder





/**
 * 
 */
package com.test.string;


import java.util.Arrays;


/**
 * @author Administrator
 *
 */
public class MyStringBUffer 
{

/**
* 数组对象
*/
private char[] value;

/**
* 长度
*/
private int count;

public MyStringBUffer ()
{
value = new char[16];
}
    
public MyStringBUffer(String str)
{
value = new char[str.length()+ 16];
append(str);
}

public MyStringBUffer append(String str)
{
if (null == str) str="null";
int len = str.length();
int newCount = len+count;

//加上原来的长度,复制新的字节数组,
value = Arrays.copyOf(value, newCount);

   //把拼接的字符串加到后面
str.getChars(0,len, value, count);
count = newCount;
return this;
}

/* 
* 重写toString
*/
public String toString()
{
return  new String(value,0,count);
}

public char[] getValue() {
return value;
}


public void setValue(char[] value) {
this.value = value;
}


public int getCount() {
return count;
}


public void setCount(int count) {
this.count = count;
}

}


你可能感兴趣的:(J2SE)