20.4 Mutable vs. Immutable Types
Last updated
Last updated
An immutable data type is one for which an instance cannot change in any observable way after instantiation.
Examples:
Mutable: ArrayDeque, Percolation.
Immutable: Integer, String, Date.
The final
keyword will help the compiler ensure immutability.
final
variable means you may assign a value once (either in the constructor of the class or in the initializer), but after it can never change.
final
is neither sufficient nor necessary for a class to be immutable.
Advantage: Less to think about; avoids bugs and makes debugging easier.
Analogy: Immutable classes have some buttons you can press / windows you can look inside. Results are ALWAYS the same, no matter what.
Disadvantage: Must create a new object anytime anything changes.
Example: String concatenation is slow!
In principle, we can create a HashSet<List>.
Weird stuff happens if:
We insert a List into a HashSet.
We later mutate that List.
Key Point: Never mutate (modify) an object being used as a key. Incorrect results arise, and the item gets lost. The slides for the Hashing II Lecture provide a very thorough visual example of this point.
In this last section, Professor Hug gives a quick walkthrough of the code for HashSets and HashMaps in Java's official implementation.