June 2018
Intermediate to advanced
280 pages
7h 46m
English
Java 9 gives us factory methods to create immutable collections. For example, to create an immutable list, we use List.of:
jshell> List immutableList = List.of("This", "is", "a", "List")immutableList ==> [This, is, a, List]jshell> immutableList.add("something")| Warning:| unchecked call to add(E) as a member of the raw type java.util.List| immutableList.add("something")| ^----------------------------^| java.lang.UnsupportedOperationException thrown:| at ImmutableCollections.uoe (ImmutableCollections.java:71)| at ImmutableCollections$AbstractImmutableList.add (ImmutableCollections.java:77)| at (#6:1)
Similarly, we have Set.of, Map.of, and Map.ofEntries. Let's take a look at the usage:
jshell> Set immutableSet ...
Read now
Unlock full access