Reputation: 752
I am looking for some efficient way for building a immutable class, just like Java's String class.
Upvotes: 1
Views: 1346
Reputation: 48255
private
and preferably final
Collections.unmodifiable*
. Also, collections should contain only immutable ObjectsTom Hawtin pointed out that final
can be optional. String
class
has a cache hash
var that is only assigned when the hash function is called.
Upvotes: 8
Reputation:
An object is immutable if none of its fields can be modified, so those fields must be final
. If you don't want your object to be subclassed, you can make the class itself final
as well, just like String is.
To easily construct an immutable object with a lot of information, you should look at the Factory Pattern
For more information, see Wikipedia
Upvotes: 1
Reputation: 12792
If you populate all fields using the constructor and make the fields final - you are partway there.
If the fields use custom types - you may need to make them immutable as well.
Any fields that are collections should use the unmodifiable collections - to be on the safe side.
You need to worry about the object graph!
Any methods on the object need to take care with non-final fields. E.g. String.add creates a new String. If you need to mutate one field - do so via a copy constructor.
Finally make the object final.
Upvotes: 1