1.不可变的类有什么好处
- are simple to construct, test, and use
- are automatically thread-safe and have no synchronization issues
- do not need a copy constructor
- do not need an implementation of clone
- allow hashCode to use lazy initialization, and to cache its return value
- do not need to be copied defensively when used as a field
- make good Map keys and Set elements (these objects must not change state while in the collection)
- have their class invariant established once upon construction, and it never needs to be checked again
- always have “failure atomicity” (a term used by Joshua Bloch) : if an immutable object throws an exception, it’s never left in an undesirable or indeterminate state
二、如何使一个类不可变
Java documentation itself has some guidelines identified in this link. We will understand what they mean actually:
1) Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.
This principle says that for all mutable properties in your class, do not provide setter methods. Setter methods are meant to change the state of object and this is what we want to prevent here.
2) Make all fields final and private
This is another way to increase immutability. Fields declared private will not be accessible outside the class and making them final will ensure the even accidentally you can not change them.
3) Don’t allow subclasses to override methods
The simplest way to do this is to declare the class as final. Final classes in java can not be overridden.
4) Special attention when having mutable instance variables
引用自:https://howtodoinjava.com/core-java/basics/how-to-make-a-java-class-immutable/
本文详细阐述了Java中不可变类的好处,包括线程安全、简化构造和测试等,并提供了实现不可变类的具体方法,如禁止提供setter方法、声明所有字段为final和private等。

被折叠的 条评论
为什么被折叠?



