109. Creating unmodifiable/immutable collections

Creating unmodifiable/immutable collections in Java can easily be accomplished by means of the Collections.unmodifiableFoo() method (for example, unmodifiableList()) and, starting with JDK 9, via the set of of() methods from List, Set, Map, and other interfaces.

Furthermore, we will use these methods in a bunch of examples to obtain unmodifiable/immutable collections. The main goal is to determine whether each defined collection is unmodifiable or immutable.

Before reading this section, it is advisable to read the problems dedicated to immutability from Chapter 2, Objects, Immutability, and Switch Expressions.

OK. In the case of primitives, it is pretty simple. For example, we can create an immutable List of integers as follows:

private static final List<Integer> LIST 
= Collections.unmodifiableList(Arrays.asList(1, 2, 3, 4, 5));

private static final List<Integer> LIST = List.of(1, 2, 3, 4, 5);

For the next examples, let's consider the following mutable class:

public class MutableMelon {

private String type;
private int weight;

// constructor omitted for brevity

public void setType(String type) {
this.type = type;
}

public void setWeight(int weight) {
this.weight = weight;
}

// getters, equals() and hashCode() omitted for brevity
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.125.51