Java Reference
In-Depth Information
confusion about which location in your code updates a collection (or any other shared data
structure) and at what point in time.
Let's look at an example to demonstrate this idea. Let's add an element to a Set:
In this example, the set of numbers isn't modified. Instead, a new Set is created with an
additional element.
Note that Scala doesn't force you to use immutable collections—it just makes it easy to adopt
immutability in your code. There are also mutable versions available in the package
scala.collection.mutable.
Unmodifiable vs. immutable
Java provides several ways to create unmodifiable collections. In the following code the variable
newNumbers is a read-only view of the set numbers:
Set<Integer> numbers = new HashSet<>();
Set<Integer> newNumbers = Collections.unmodifiableSet(numbers);
This means you won't be able to add new elements through the newNumbers variable. But an
unmodifiable collection is just a wrapper over a modifiable collection. This means that you could
still add elements by accessing the numbers variable!
By contrast, immutable collections guarantee that nothing can change the collection, regardless
of how many variables are pointing to it.
We explained in chapter 14 how you could create a persistent data structure: an immutable data
structure that preserves the previous version of itself when modified. Any modifications always
produce a new updated structure.
Search WWH ::




Custom Search