String StringBuilder StringBuffer 用法比较

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

String、StringBuilder、StringBuffer 三个类源自JDK的  java/lang/ 目录下:

String 字符串常量
StringBuffer 字符串变量(线程安全)
StringBuilder 字符串变量(非线程安全,JDK 5.0(1.5.0) 后支持)


String
 简要的说, String 类型和 StringBuffer 类型的主要性能区别其实在于 String 是不可变的对象, 因此在每次对 String 类型进行改变的时候其实都等同于生成了一个新的 String 对象,然后将指针指向新的 String 对象,所以经常改变内容的字符串最好不要用 String ,因为每次生成对象都会对系统性能产生影响,特别当内存中无引用对象多了以后, JVM 的 GC 就会开始工作,那速度是一定会相当慢的。

String 构造函数:

 private final char value[];    private final int offset;    private final int count;  public String() {        this.offset = 0;        this.count = 0;        this.value = new char[0];    }  public String(String original) {        int size = original.count;        char[] originalValue = original.value;        char[] v;        if (originalValue.length > size) {            // The array representing the String is bigger than the new            // String itself.  Perhaps this constructor is being called            // in order to trim the baggage, so make a copy of the array.            int off = original.offset;            v = Arrays.copyOfRange(originalValue, off, off+size);        } else {            // The array representing the String is the same            // size as the String, so no point in making a copy.            v = originalValue;        }        this.offset = 0;        this.count = size;        this.value = v;    }  public String(char value[]) {        int size = value.length;        this.offset = 0;        this.count = size;        this.value = Arrays.copyOf(value, size);    }  public String(char value[], int offset, int count) {        if (offset < 0) {            throw new StringIndexOutOfBoundsException(offset);        }        if (count < 0) {            throw new StringIndexOutOfBoundsException(count);        }        // Note: offset or count might be near -1>>>1.        if (offset > value.length - count) {            throw new StringIndexOutOfBoundsException(offset + count);        }        this.offset = 0;        this.count = count;        this.value = Arrays.copyOfRange(value, offset, offset+count);    }  public String substring(int beginIndex, int endIndex) {        if (beginIndex < 0) {            throw new StringIndexOutOfBoundsException(beginIndex);        }        if (endIndex > count) {            throw new StringIndexOutOfBoundsException(endIndex);        }        if (beginIndex > endIndex) {            throw new StringIndexOutOfBoundsException(endIndex - beginIndex);        }        return ((beginIndex == 0) && (endIndex == count)) ? this :            new String(offset + beginIndex, endIndex - beginIndex, value);  // 返回新对象    }  public String concat(String str) {        int otherLen = str.length();        if (otherLen == 0) {            return this;        }        char buf[] = new char[count + otherLen];        getChars(0, count, buf, 0);        str.getChars(0, otherLen, buf, count);        return new String(0, count + otherLen, buf);  // 返回新对象    }  public static String valueOf(char data[]) {        return new String(data);  // 返回新对象    }  public static String valueOf(char c) {        char data[] = {c};        return new String(0, 1, data);  // 返回新对象    }

StringBuffer
StringBuffer 每次对对象本身进行操作,而不是生成新的对象,再改变对象引用。所以在一般情况下我们推荐使用 StringBuffer ,特别是字符串对象经常改变的情况下。

StringBuffer 构造函数:

 public StringBuffer() {        super(16);    }  public StringBuffer(int capacity) {        super(capacity);    }  public StringBuffer(String str) {        super(str.length() + 16);        append(str);    }  public StringBuffer(CharSequence seq) {        this(seq.length() + 16);        append(seq);    }  public synchronized int length() {  // 字节实际长度        return count;    }  public synchronized int capacity() // 字节存储容量(value数组的长度)        return value.length;    }  public synchronized void ensureCapacity(int minimumCapacity) {        if (minimumCapacity > value.length) {            expandCapacity(minimumCapacity);        }    }  public synchronized StringBuffer append(Object obj) {        super.append(String.valueOf(obj));        return this// 返回对象本身    }  public synchronized StringBuffer append(String str) {        super.append(str);        return this// 返回对象本身    }  public synchronized StringBuffer append(StringBuffer sb) {        super.append(sb);        return this// 返回对象本身    }


而在某些特别情况下, String 对象的字符串拼接其实是被 JVM 解释成了 StringBuffer 对象的拼接,所以这些时候 String 对象的速度并不会比 StringBuffer 对象慢,而特别是以下的字符串对象生成中, String 效率是远要比 StringBuffer 快的:
 String S1 = “This is only a” + “ simple” + “ test”;
 StringBuffer Sb = new StringBuilder(“This is only a”).append(“ simple”).append(“ test”);
 你会很惊讶的发现,生成 String S1 对象的速度简直太快了,而这个时候 StringBuffer 居然速度上根本一点都不占优势。其实这是 JVM 的一个把戏,在 JVM 眼里,这个
 String S1 = “This is only a” + “ simple” + “test”; 

其实就是:
 String S1 = “This is only a simple test”; 

所以当然不需要太多的时间了。但大家这里要注意的是,如果你的字符串是来自另外的 String 对象的话,速度就没那么快了,譬如:
String S2 = “This is only a”;
String S3 = “ simple”;
String S4 = “ test”;
String S1 = S2 +S3 + S4;
这时候 JVM 会规规矩矩的按照原来的方式去做

在大部分情况下: StringBuffer > String

Java.lang.StringBuffer线程安全的可变字符序列。一个类似于 String 的字符串缓冲区,但不能修改。虽然在任意时间点上它都包含某种特定的字符序列,但通过某些方法调用可以改变该序列的长度和内容。
可将字符串缓冲区安全地用于多个线程。可以在必要时对这些方法进行同步,因此任意特定实例上的所有操作就好像是以串行顺序发生的,该顺序与所涉及的每个线程进行的方法调用顺序一致。
StringBuffer 上的主要操作是 append 和 insert 方法,可重载这些方法,以接受任意类型的数据。每个方法都能有效地将给定的数据转换成字符串,然后将该字符串的字符追加或插入到字符串缓冲区中。append 方法始终将这些字符添加到缓冲区的末端;而 insert 方法则在指定的点添加字符。
例如,如果 z 引用一个当前内容是“start”的字符串缓冲区对象,则此方法调用 z.append("le") 会使字符串缓冲区包含“startle”,而 z.insert(4, "le") 将更改字符串缓冲区,使之包含“starlet”。

StringBuilder
java.lang.StringBuilder一个可变的字符序列是5.0新增的。此类提供一个与 StringBuffer 兼容的 API,但不同步。该类被设计用作 StringBuffer 的一个简易替换,用在字符串缓冲区被单个线程使用的时候(这种情况很普遍)。如果可能,建议优先采用该类,因为在大多数实现中,它比 StringBuffer 要快。两者的方法基本相同。

StringBuilder 构造函数:

 public StringBuilder() {        super(16);    }  public StringBuilder(int capacity) {        super(capacity);    }  public StringBuilder(String str) {        super(str.length() + 16);        append(str);    }  public StringBuilder(CharSequence seq) {        this(seq.length() + 16);        append(seq);    }  public StringBuilder append(Object obj) {        return append(String.valueOf(obj));    }    public StringBuilder append(String str) {        super.append(str);        return this// 返回对象本身    }  private StringBuilder append(StringBuilder sb) {        if (sb == null)            return append("null");        int len = sb.length();        int newcount = count + len;        if (newcount > value.length)            expandCapacity(newcount);        sb.getChars(0, len, value, count);        count = newcount;        return this// 返回对象本身    }  public StringBuilder append(StringBuffer sb) {        super.append(sb);        return this// 返回对象本身    }

在大部分情况下: StringBuilder > StringBuffer


总结

StringBuffer 和 StringBuilder 都继承于 AbstractStringBuilder 父类,实现了java.io.Serializable, CharSequence

AbstractStringBuilder 父类构造函数:

 char[] value;  // 字符数组  AbstractStringBuilder() {    }  AbstractStringBuilder(int capacity) {        value = new char[capacity];  // 申请字节存储容量    }  public int length() {        return count;   // 返回实际字节长度    }  public int capacity() {        return value.length; // 返回字节存储容量    }  public void ensureCapacity(int minimumCapacity) {        if (minimumCapacity > 0)            ensureCapacityInternal(minimumCapacity); // 扩展容量大小    }  private void ensureCapacityInternal(int minimumCapacity) {        // overflow-conscious code        if (minimumCapacity - value.length > 0)  // 如果设置的最小容量 > 当前字节存储容量            expandCapacity(minimumCapacity);    }  void expandCapacity(int minimumCapacity) {        int newCapacity = value.length * 2 + 2;  // 自动新增容量,为当前容量的2倍加2(java是unicode编码,占两个字节)        if (newCapacity - minimumCapacity < 0)            newCapacity = minimumCapacity;        if (newCapacity < 0) {            if (minimumCapacity < 0) // overflow                throw new OutOfMemoryError();            newCapacity = Integer.MAX_VALUE;        }        value = Arrays.copyOf(value, newCapacity);    }  public AbstractStringBuilder append(Object obj) {        return append(String.valueOf(obj));    }  public AbstractStringBuilder append(String str) {        if (str == null) str = "null";        int len = str.length();        ensureCapacityInternal(count + len);        str.getChars(0, len, value, count);        count += len;        return this;  // 返回对象本身    }  public AbstractStringBuilder append(StringBuffer sb) {        if (sb == null)            return append("null");        int len = sb.length();        ensureCapacityInternal(count + len);        sb.getChars(0, len, value, count);        count += len;        return this;  // 返回对象本身    }  public AbstractStringBuilder append(CharSequence s) {        if (s == null)            s = "null";        if (s instanceof String)            return this.append((String)s);        if (s instanceof StringBuffer)            return this.append((StringBuffer)s);        return this.append(s, 0, s.length());  // 返回对象本身    }

关于String更多的介绍,请详见我先前写的博客:Java 之 String 类型

在大部分情况下,三者的效率如下:

StringBuilde > StringBuffer > String



参考推荐:

StringBuilder、StringBuffer、String 的区别

Java 之 String 类型



           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow
这里写图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!
提供的源码资源涵盖了小程序应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值