I don’t know either my implementation have bugs or StringBuilder is going wrong. From the stackoverflow, i got to know that Java Strings are immutable. Currently i am doing some string processing in a recursive fashion using StringBuilder. To make recursion more clear and understandable i am using a Queue to store StringBuilder. The same processing can be done with Strings but it will increase the execution time, so i am using StringBuilder. The input string is first converted to StringBuilder then added to Queue after that a for loop matches it character and replaces substring with a char. This resultant StringBUilder is added to the Queue. Then an element(StringBuilder) is removed from the Queue and processed with for loop in the same previous manner. This process is repeated until the Queue is not empty. Below is my code snippet-
Queue<StringBuilder> q = new LinkedList<StringBuilder>();
StringBuilder sb;
q.add(new StringBuilder("abcccc"));
while ((sb = q.poll()) != null) {
int len = sb.length();
for (int i = 0; i < len - 1; i++) {
/*
* Here i am matching charAt(i) with charAt(i+1) and based on
* the characters matching decision is done
*/
StringBuilder rep = new StringBuilder(len - 1);
rep = sb;
rep.replace(i, i + 2, replace);//replace is a string which is a character
q.add(rep);
}
}
This gives me StringIndexOutOfBoundsException. However i am not changing the content of original StringBuilder, which is sb. I am just creating a copy of sb which is rep, then replacing the content of this newly created StringBuilder.
rep = sbis not creating a copy ofsb. Both of those objects are now pointing to the same StringBuilder instance.