The difference between String and StringBuilder and their internal organization

This is a very simple question. The extent of the answer I know is that the strings are immutable. There are no Stringbuilders, so you can add characters at the end.

So, how are builders under construction? String is an array of characters.

Is StringBuilder an array of characters? So, I have StringBuilder MY_OBJ = "Hello". Now, if I try to add characters to the end of MY_OBJ, does this mean that you are actually creating a new array object and copying all these characters into a new one? If so, how is this more efficient than a string?

And another question I have in mind is how can the end of StringBuilder be marked? As in C, we use "/ 0"

+5
source share
3 answers

I dont know. Release:

72   public final class StringBuilder
73       extends AbstractStringBuilder
45        * The value is used for character storage.
46        */
47       char[] value;
48   
49       /**
50        * The count is the number of characters used.
51        */
52       int count;

===

Is StringBuilder an array of characters?

Apparently in this particular implementation.

So, I have StringBuilder MY_OBJ = "Hello". Now, if I try to add characters to the end of MY_OBJ, does this mean that you are actually creating a new array object and copying all these characters into a new one?

Not necessary. The array is not necessarily filled ( count < value.length), so a new array may not be needed. Ideally, you initialize StringBuilder with a capacity so that a sufficiently large array is allocated from the very beginning.

StringBuilder sb = new StringBuilder(20);
sb.append("Hello");
...
sb.append(" there");

, , - StringBuilder? C, "/0"

- String/StringBuilder .

+8

StringBuilder AbstractStringBuilder, Sun - char. , count, , . , , ( trimToSize, , , ).

, , , arrayCopy, , , , , . , , , , , .

, :

StringBuilder MY_OBJ= "Hello";

.

:

StringBuilder MY_OBJ= new StringBuilder("Hello");
+6

StringBuilder , String, . , / / .

StringBuilder , 16 char. #append(String) StringBuidler String#getChars(int, int, char[], int). , Arrays.copyOf(char[], int), . , , . .

Java + String. StringBuilder , .

StringBuilder, StringBuilder#trimToSize() , . .

Hope this helps.

+1
source

All Articles