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.
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()
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(); '