Java 10 Immutable Collection Copy
- schick09
- Oct 27, 2024
- 1 min read
Java 10 introduced the ability to create an immutable copy of a collection. The following static methods were added:
List.copyOf(), Set.copyOf(), and Map.copyOf()
Keep in mind that changes to the underlying collection are NOT reflected in the copy. If you make updates to the underlying collection the changes aren't applied to the copy (because it's...well...immutable).
Let's start by creating a source collection we want to eventually copy:
List<String> sourceCollection = new ArrayList<String>( Arrays.asList("one", "two", "three"));
Now let's create an immutable copy of this collection:
List<String> copiedCollection = List.copyOf(sourceCollection);
What happens if you try to add an element to the immutable 'copiedCollecton'? Let's find out:
copiedCollection.add("four");
Just as you'd expect, it throws an UnsupportedOperationException:
Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:72) at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:76) at funwithimmutablecollectioncopies.funwithlocalvariabletypeinference.Main.main(Main.java:36)
Now let's modify the underlying source collection by adding an element:
sourceCollection.add("four");
And finally, we will prove that the sourceCollection allowed the element "four" to be added and the copiedCollection did not:
assert(!copiedCollection.stream().anyMatch("four"::equals)); assert(sourceCollection.stream().anyMatch("four"::equals));
If you wanted a copy of the list that you could modify, then do the following:
List<String> copy = new ArrayList<>(sourceCollection);
Here's a link to our GitHub location to access an example of creating an immutable copy of a Collection: https://github.com/daveschickconsulting/java_10_examples/tree/main/src/funwithimmutablecollectioncopies




Comments