定义自己StringBuilder
来源:互联网 发布:java递归删除树节点 编辑:程序博客网 时间:2024/06/05 23:42
import java.util.Arrays;public class MyStringBuilderDemo{public static void main(String[] args){MyStringBuilder msb1=new MyStringBuilder();msb1.append("hello").append(" world").append(".helloworldhello");System.out.println(msb1.length());System.out.println(msb1.totallength());System.out.println(msb1.toString());MyStringBuilder msb2=new MyStringBuilder(32);msb2.append("hello").append(" world").append(".helloworldhello");System.out.println(msb2.length());System.out.println(msb2.length());System.out.println(msb2.totallength());System.out.println(msb2.toString());MyStringBuilder msb3=new MyStringBuilder("helloworld");msb3.append("nihaohello");System.out.println(msb3.toString());}}class MyStringBuilder{private char[] values;private int count=0;public MyStringBuilder(){values=new char[16];}public MyStringBuilder(int num){values=new char[num];}public MyStringBuilder(String str){values=new char[str.length()];count=str.length();values=str.toCharArray();}//返回字符串的长度public int length(){return count;}//返回总容量的方法public int totallength(){return values.length;}//用来追加字符串的方法public MyStringBuilder append(String str){panduan(count+str.length());char[] chars=str.toCharArray();System.arraycopy(chars,0,values,count,str.length());count+=str.length();return this;}//输出MyStringBuilder中的字符串public String toString(){String str=String.copyValueOf(values,0,count);return str;}//用来判断字符长度是否超出了private void panduan(int num){if(num-values.length>0){int newlength=values.length*2+2;values=Arrays.copyOf(values,newlength);}} }
阅读全文