# 20.4 Mutable vs. Immutable Types

## Immutable Data Types

{% embed url="https://www.youtube.com/watch?index=6&list=PL8FaHk7qbOD637Q-6p7nn5dKz1tK6WAjJ&v=fHuU2zeBwIs" %}

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.

```java
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!

<figure><img src="https://2316889115-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FCLYj7ccqvV6l4Pt9R0w5%2Fuploads%2FxntDEehjkP4E4EE6wmqz%2Fimage.png?alt=media&#x26;token=690427cc-9f86-478f-81fa-323eac3d2268" alt=""><figcaption></figcaption></figure>

## Mutable Types

{% embed url="https://www.youtube.com/watch?index=7&list=PL8FaHk7qbOD637Q-6p7nn5dKz1tK6WAjJ&v=7lqlRGO_mGY" %}

### **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 ](https://docs.google.com/presentation/d/1U_-RQCJB3j9B-k-kY8I4nS-FuxIvO8EgVIrOthx2InU/edit#slide=id.g2165b69ef3f_0_291)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.

{% embed url="https://youtu.be/pc5SDicUqWo" %}
