What is the difference between mutable and immutable?
Such as:
NSString vs NSMutableString.
NSArray vs NSMutableArray.
NSDictionary vs NSMutableDictionary.
What is the difference between a mutable object and the other object [which I assume is immutable]?
If the value can change, the object is called mutable, while if the value cannot change, the object is called immutable.
The mutable class examples are StringBuffer, Java. util. Date, StringBuilder, etc. Whereas the immutable objects are legacy classes, wrapper classes, String class, etc.
Core Java bootcamp program with Hands on practice On the other hand, Mutable objects have fields that can be changed, immutable objects have no fields that can be changed after the object is created. Sr. No. We can't modify the state of the object after it is created.
Summary. An object whose internal state cannot be changed is called immutable for example a number, a string, and a tuple. An object whose internal state can be changed is called mutable for example a list, a set, and a dictionary.
A mutable object can be mutated or changed. An immutable object cannot. For example, while you can add or remove objects from an NSMutableArray, you cannot do either with an NSArray.
Mutable objects can have elements changed, added to, or removed, which cannot be achieved with immutable objects. Immutable objects are stuck with whatever input you gave them in their [[object alloc] initWith...]
initializer.
The advantages of your mutable objects is obvious, but they should only be used when necessary (which is a lot less often than you think) as they take up more memory than immutable objects.
Mutable objects can be modified, immutable objects can't.
Eg:
NSMutableArray has addObject:
removeObject:
methods (and more), but NSArray doesn't.
Modifying strings:
NSString *myString = @"hello";
myString = [myString stringByAppendingString:@" world"];
vs
NSMutableString *myString = @"hello";
[myString appendString:@" world"];
Mutable objects are particularly useful when dealing with arrays,
Eg if you have an NSArray of NSMutableStrings you can do:
[myArray makeObjectsPerformSelector:@selector(appendString:) withObject:@"!!!"];
which will add 3 ! to the end of each string in the array.
But if you have an NSArray of NSStrings (therefore immutable), you can't do this (at least it's a lot harder, and more code, than using NSMutableString)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With