Why is this problem? First, let's take a look at the differences between string and stringbuffer:
= Only two strings can be compared for the same memory address, not the string content;
The string equals method can compare the content of the string because it overwrites the object's equals method. stringbuffer does not overwrite the equals method.
By the way, because string is of the final type and is an immutable class, operations such as append must be re-added to the new string, while stringbuffer is a mutable class, no new stringbuffer is required, so the performance of string operations is very good, and the performance is not a little better. Try:
1 public static void main(String[] args) { 2 StringBuffer s1 = new StringBuffer(); 3 String s2 = new String(); 4 5 Date d = new Date(); 6 long a = d.getTime(); 7 for (int i = 0; i < 100000; i++) { 8 s1.append(i); 9 }10 Date d2 = new Date();11 long b = d2.getTime();12 System.out.println(b-a);13 14 Date d3 = new Date();15 a = d3.getTime();16 for (int i = 0; i < 100000; i++) {17 s2 = s2 + i;18 }19 Date d4 = new Date();20 b = d4.getTime();21 System.out.println(b-a);22 }
So how can we compare whether the content of stringbuffer strings is equal?
You can use the tostring () method to convert the content of stringbuffer to a string, and then use the equals () method for comparison.
1 public class main {2 public static void main (string [] ARGs) {3 stringbuffer strb1 = new stringbuffer ("Java "); // create stringbuffer object str1 4 stringbuffer strb2 = new stringbuffer ("Java"); // create stringbuffer object str2 5 system. out. println ("***** do not use the tostring () method *****"); 6 if (strb1.equals (strb2) {7 system. out. println ("Equal"); 8} else {9 system. out. println ("not equal"); 10} 11 system. out. println ("***** use the tostring () method *****"); 12 if (strb1.tostring (). equals (strb2.tostring () {13 system. out. println ("Equal"); 14} else {15 system. out. println ("not equal"); 16} 17} 18}
Is the stringbuffer string content equal?