Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is difference between mutable and immutable

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]?

like image 633
user891268 Avatar asked Aug 15 '11 21:08

user891268


People also ask

What is the difference between mutable and immutable type?

If the value can change, the object is called mutable, while if the value cannot change, the object is called immutable.

What is mutable and immutable with example?

The mutable class examples are StringBuffer, Java. util. Date, StringBuilder, etc. Whereas the immutable objects are legacy classes, wrapper classes, String class, etc.

What is difference between mutable and immutable in Java?

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.

What is mutable and immutable in Python with example?

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.


2 Answers

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.

like image 87
Benjamin Mayo Avatar answered Oct 11 '22 09:10

Benjamin Mayo


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)

like image 32
Jonathan. Avatar answered Oct 11 '22 09:10

Jonathan.