简体   繁体   中英

How to get character array which is inside StringBuilder to avoid array copy

Is there any way by which I can get character array stored inside StringBuilder to avoid creating copy of it when I do toString(). Since, it is a primitive array so it is like deep copy and I would like to avoid generating this garbage.

You can treat the StringBuilder as a char[] , the bridge is supported by the interface CharSequnce

Calling the method charAt(int index) is "equal to" array[index]

The array is a private field that is not exposed to the public customer, due to encapsulation.

Avoid doing stringbuilder.toString().toCharArray() as it will allocate the memory twice.

Use something like :

char[] charArray = new char[stringbuilder.length()];
stringbuilder.getChars(0, stringbuilder.length(), charArray, 0);

Using reflection is also a bad idea as it may not be compatible with future java version and you'll have to resize the array as its size is probably bigger than the StringBuilder length see StringBuilder#capacity()

No, you can't.

Check the source of StringBuilder .

char value[] is the character array stored inside StringBuilder, and it's reference can be accessed only through getValue method, which is NOT public.

Therefore, either use toString or getChars

You can do this using reflection:

Field stringbuilderCharField = StringBuilder.class.getSuperclass().getDeclaredField("value"); 
stringbuilderCharField.setAccessible(true);
char[] charArray = (char[]) stringbuilderCharField.get(pString);

And as StringBuilder is mutable, this is actually a nice way to use it. You can do the same for String, but not advisable, as String is immutable.

Let us suppose 'str' is an instance of StringBuilder class that holds some string. The simplest way to convert str to char array is as follows:

' str.toString().toCharArray(); '

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM