The difference and use of String, StringBuffer, StringBuilder based on Java

First, let's talk about the similarities between String, StringBuffer, and StringBuilder .
These three are all used to encapsulate strings , as
Inheritance diagramcan be seen from the figure, all three are inherited from the CharSequence interface.
Next, let’s talk about the differences between the three!

One of the differences:

The value of String cannot be changed from creation to destruction.
The StringBuffer and StringBuilder inherit from the AbstractStringBuilder class, which is stored in a character array, so it is variable.
So the usage scenarios:
String to save the infrequent changes, StringBuffer and StringBuilder to save the frequently changed. Imagine if you use String to store variable, then every time a new object is created and the old object is recycled, it will affect the performance of the program.
The method of string modification is to first create a StringBuffer, then call the append method of StringBuffer, and finally call the toString() method to return the result

代码:
String str = "王";
str += "胖子";

实际进行的操作:
StringBuffer sb = new StringBuffer(str);
sb.append("胖子");
str = sb.toString();

The second difference:

Way of creation:

        // String 可以赋值或构造器
        String a="王小胖";
        String b=new String("王二胖");
        // StringBuffer 构造器
        StringBuffer c=new StringBuffer("王瘦瘦");
        // StringBuilder 构造器
        StringBuilder d=new StringBuilder("王小瘦");

The third difference:

The equals and hashCode methods
String implements equals() and hashCode() methods, so the result of new String("java").equals(new String("java")) is true;

StringBuffer does not implement equals() method and hashCode() method. Therefore, the result of new StringBuffer("java").equals(new StringBuffer("java")) is false, and the StringBuffer object stored in the Java collection class will appear problem.

Four different points:

Scenarios used:
StringBuffer and StringBuilder both have the function of modifying strings, and the usage is similar, except:
String: The number of operations is small,
StringBuilder is unsafe for single-threaded operations, and
StringBuffer is thread-safe for multi-threaded operations for large amounts of data.

Guess you like

Origin blog.csdn.net/Pzzzz_wwy/article/details/105469792