Possible Duplicate:
Why do we need immutable class?
Can anyone give me an example of a real world use of immutable class in java? What is the real purpose? For example wh开发者_开发知识库y is String immutable
One reason is that immutable classes are thread-safe.
Because it is difficult (and sometimes inefficient) to correctly manage shared mutable state. If String
weren't immutable, each method would have to be made thread-safe and allow for the contents of the string to change. Being immutable in this case means that no locking is necessary, since the only thing you can do with a string is to read it.
This is one of the major benefits of functional programming languages; where all state is immutable (i.e. destructive updates are not allowed).
An immutable class is immutable so that any object with existing references to the object won't mess up, which are reliant on the information inside the object staying the same. It comes at a slight hit to efficiency in some cases, but the trade-off is reliability and stability. It basically means that a new object is created for each of the methods used.
精彩评论