MyStringBuild

                                       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());
 }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值