20.4 Mutable vs. Immutable Types

Immutable Data Types

An immutable data type is one for which an instance cannot change in any observable way after instantiation.


  • Mutable: ArrayDeque, Percolation.

  • Immutable: Integer, String, Date.

public class Date {
   public final int month;
   public final int day;
   public final int year;
   private boolean contrived = true;
   public Date(int m, int d, int y) {
       month = m; day = d; year = y;

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.

Advantages vs. Disadvantages of Immutability:

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!

Mutable Types

Mutable HashSet Keys

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.

Actual Implementation of HashSet/Map in Java

In this last section, Professor Hug gives a quick walkthrough of the code for HashSets and HashMaps in Java's official implementation.

Last updated