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 ??
String, StringBuilder and StringBuffer all use a char for internal storage. The main difference is, String does not have any methods that allows you to change that array, whereas StringBuilder and StringBuffer do.
Your MutableString class should simply have methods that allows you to change that array. It could look like this (very naive and simple implementation):
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.