IT评测·应用市场-qidao123.com

标题: String、StringBuffer、StringBuilder 的区别? [打印本页]

作者: 飞不高    时间: 2023-7-10 00:18
标题: String、StringBuffer、StringBuilder 的区别?
一. 介绍 String、StringBuffer、StringBuilder:  
   前言: String、StringBuffer、StringBuilder 均在java.lang包下;
    String: 在Java中,String是一个特殊的引用类型,用于表示文本字符串。它提供了许多方法来操作和处理字符串,比如连接、截取、查找、替换等。String类内部使用字符数组(char[])来存储字符串的内容,且value字段被final修饰,这意味着String对象一旦创建后,其值就不可改变。String对象的值存储在常量池中,每次修改操作都会创建一个新的字符串对象,并且如果常量池中已经存在相同内容的字符串,就会直接引用该字符串而不创建新对象。
    StringBuffer:Java中的一个可变字符串类,用于处理字符串。它可以被修改,因此适合在需要频繁更改字符串内容的情况下使用。StringBuffer提供了许多方法用于插入、删除和修改字符串,并且支持线程安全操作。与String类不同,StringBuffer对象可以在已有的字符串基础上进行操作,且地址值不会改变;StringBuffer 类是可变的,它不会在常量池中创建新的常量。当你使用 StringBuffer 修改一个字符串时,它会在堆内存中创建一个新的字符串对象,并且在需要的时候调整其容量。
    StringBuilder:与StringBuffer类似,它允许在已有字符串的基础上进行修改、添加和删除操作,而不需要创建新的字符串对象。通过使用StringBuilder,可以高效地进行字符串拼接、插入、替换等操作,特别适用于频繁修改字符串内容的场景,每次修改只是对自身做出修改。StringBuilder具有较高的性能和效率,并且是线程不安全的,适用于单线程环境下的字符串处理。
 
二. 区别:
  1. 不可变性:
  2. 线程安全性:
  3. 性能:
  综上所述,如果你需要进行频繁的字符串拼接、替换等操作,并且在多线程环境下使用,应该选择StringBuffer类。如果在单线程环境下进行字符串操作,可以选择StringBuilder类以获得更好的性能。而如果你不需要修改字符串,只是进行简单的字符串操作,那么使用String类即可。
 
三. 代码展示
 不可变性区别展示:
  1. public static void main(String[] args) {
  2.        // String
  3.         String str = "Hello";
  4.         System.out.println(System.identityHashCode(str));
  5.         String str1 = str + "word";
  6.         System.out.println(System.identityHashCode(str1));
  7.        // StringBuilder
  8.         StringBuilder sb = new StringBuilder("Hello");
  9.         System.out.println(System.identityHashCode(sb));
  10.         StringBuilder sb1 = sb.append("word");
  11.         System.out.println(System.identityHashCode(sb1));
  12.        // StringBuffer
  13.         StringBuffer sbf = new StringBuffer("Hello");
  14.         System.out.println(System.identityHashCode(sbf));
  15.         StringBuffer sbf1 = sbf.append("word");
  16.         System.out.println(System.identityHashCode(sbf1));
  17.     }
  18. 输出结果:
  19.     23934342
  20.     22307196
  21.     10568834
  22.     10568834
  23.     21029277
  24.     21029277<br><br>// 此方法中可以看到String是不可变,每次修改操作都会创建一个新的字符串对象,而StringBuffer、StringBuilder每次修改都不会改变自身的地址。
复制代码
  JAVA是在jvm虚拟机上运行的,只能查看jvm中地址的哈希码,要想得到String类型在物理内存中的真实地存,那只有用JNI技术调用c/c++去实现,因此使用identityHashCode() ,该方法会返回对象的hashCode,不管对象是否重写了hashCode方法。
 
四. 总结
 
五. 扩展
  1. String 源码中注释
  1. * Strings are constant; their values cannot be changed after they
  2. * are created. String buffers support mutable strings.
  3. * Because String objects are immutable they can be shared.
复制代码
    *字符串是常量;它们的值在创建后不能更改,因为String对象是不可变的,所以它们可以共享。
  1. public final class String
  2.     implements java.io.Serializable, Comparable<String>, CharSequence {
  3.     /** The value is used for character storage. */
  4.     private final char value[];
  5.     /** Cache the hash code for the string */
  6.     private int hash; // Default to 0
  7. }
复制代码
   private final char value[];  底层是字符数组实现,该值是使用final修饰,创建后不能改变。 
 
  2. StringBuffer 源码中注释
  1. * A thread-safe, mutable sequence of characters.
  2. * A string buffer is like a {@link String}, but can be modified.
  3. * The principal operations on a {@code StringBuffer} are the
  4. * {@code append} and {@code insert} methods, which are
  5. * overloaded so as to accept data of any type.
  6. * Whenever an operation occurs involving a source sequence (such as
  7. * appending or inserting from a source sequence), this class synchronizes
  8. * only on the string buffer performing the operation, not on the source.
复制代码
  * 线程安全的可变字符序列,字符串缓冲区类似于String,但是可以修改。
  * 主要操作是通过append()、insert() 它们是重载的,以便接受任何类型的数据。
  * 每当涉及到源数据的操作发生改变时,(例如从源序列追加或插入)此类进行同步仅在执行操作的字符串缓冲区上,而不是在源数据上。
  1.     @Override
  2.     public synchronized StringBuffer append(Object obj) {
  3.         toStringCache = null;
  4.         super.append(String.valueOf(obj));
  5.         return this;
  6.     }
  7.     @Override
  8.     public synchronized StringBuffer append(String str) {
  9.         toStringCache = null;
  10.         super.append(str);
  11.         return this;
  12.     }
复制代码
   StringBuffer 在插入或修改的时候 都会使用synchronized() 确保线程安全性。
 
  3. StringBuilder 源码注释
  1. * A mutable sequence of characters.  This class provides an API compatible
  2. * with {@code StringBuffer}, but with no guarantee of synchronization.
  3. * This class is designed for use as a drop-in replacement for
  4. * {@code StringBuffer} in places where the string buffer was being
  5. * used by a single thread (as is generally the case).   Where possible,
  6. * it is recommended that this class be used in preference to
  7. * {@code StringBuffer} as it will be faster under most implementations.
  8. * Instances of {@code StringBuilder} are not safe for
  9. * use by multiple threads. If such synchronization is required then it is
  10. * recommended that {@link java.lang.StringBuffer} be used.
复制代码
  * 可变的字符串,此类提供与StringBuffer兼容的API,但不保证同步。这个类通常情况下用在字符串缓冲区被单个线程使用的地方,作为StringBuffer的替代品。建议优先使用此类而不是StringBuffer,因为在大多数实现中它会更快。
   * StringBuilder的实例对于多个线程使用是不安全的。如果需要同步,则建议使用StringBuffer
  1.     @Override
  2.     public StringBuilder append(Object obj) {
  3.         return append(String.valueOf(obj));
  4.     }
  5.     @Override
  6.     public StringBuilder append(String str) {
  7.         super.append(str);
  8.         return this;
  9.     }
复制代码
  如果需要线程安全同步,建议使用StringBuffer类。
 
(๑′ᴗ‵๑) 完! 
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4