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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With