Suppose I have the following code:
StringBuilder sb = new StringBuilder("521,214"); String[] result = sb.toString().split(","); My question is: does toString().split(",") generate 2 strings or 3 strings? I know that the result String array will have 2 strings - but the toString() call will also generate a string as well - that isn't returned?
Basically, I'm trying to limit the number of strings created for performance purposes and want to know if the toString() call brings the total number of strings created to 3?
3 Answers
There will be five String object created in total by these two lines:
"521,214"object passed toStringBuilder's constructor. This object is in the interned pool of strings,","String object passed tosplit. This object is also in the interned pool of strings,- An equivalent
"521,214"object produced bytoString. Each call oftoStringproduces a newStringobject. There is no optimization to see if in identical string object has been requested before. - Two
Stringobjects for"521"and"214"produced by thesplitmethod
It goes without saying that a String[] array object will be created to hold "521" and "214" objects returned from the split method.
does toString().split(",") generate 2 strings or 3 strings
neither 2 nor 3, split returns an array object, that the array has been made of strings is another story...
if your question is how many strings are in that array then the answer is: it depends of how many tockens (",") are found in the original string that you are splitting...
It will create a String array with 2 strings in it.
You can test this anytime by printing out the array:
StringBuilder sb = new StringBuilder("521,214"); String[] result = sb.toString().split(","); for(String s : result) System.out.println(s); The method .split() will remove the string that you are splitting by.