Making custom StringBuilder (or StringBuffer) - forget thread-safe / unsafe
Joined: Feb 24, 2008
I am writing here after quite some time.
I am faced with a problem - what does String class actually do to make its objects immutable or in other words, how does StringBuilder(or StringBuffer) differ from String class in that their objects are mutable ?
I mean what code in String ( or StringBuffer, for that matter ) makes it behave the way it does behave ?
For example, lets assume that we only have String class in java that makes immutable objects and we don't have StringBuilder or StringBuffer for making mutable objects and we need that functionality. So how should I make my "MutableString" class so that when I make its objects they are mutable ??
alright. The code that you have provided is pretty straight forward and simple to understand. But it still does make use of String object which is immutable. So the purpose of having "MutableString" has been defeated..!
But thanks anyways for trying to answer my query.
Actually I was thinking on the lines of string constant pool that JVM maintains. This is the space that it looks at whenever a String object is made. If it's content is available over there then it doesn't make a new String object and simply directs the String reference to that location.
vaibhav panghal wrote:alright. The code that you have provided is pretty straight forward and simple to understand. But it still does make use of String object which is immutable. So the purpose of having "MutableString" has been defeated..!
Then replace String with MutableString, and give your class methods for retrieving the length and any character.
In fact, let's make it a bit better:
This way your add method can accept anything: String, StringBuilder, StringBuffer, but also MutableString itself.
Of course this class is very inefficient; nearly every addition will lead to a resize of the array. StringBuilder and StringBuffer solve this by having the array size duplicate each time it becomes too small; this gives you extra space for future additions.