Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

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.

like image 911
sky Avatar asked Dec 11 '13 10:12

sky


2 Answers

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()

like image 149
benbenw Avatar answered Nov 15 '22 14:11

benbenw


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

like image 29
Infinite Recursion Avatar answered Nov 15 '22 12:11

Infinite Recursion