Java 9 makes it easier to create immutable lists using its new static Factory Methods.
object. For a static List of (E e1, E e2, E e3):
jshell> List.of("one","two","three")
$2 ==> [one, two, three]
| created scratch variable $2 : List<String>
Again, note the inference as a List object.
The number of arguments keeps increasing until E e10, at which point we can use vararg.
Map Similarly, Map defines a:
static Map of ()
static Map of (K k1, V v1) to (K k10, V v10)
static Map ofEntries (Map.Entry
… entries) – note the use of Map.Entry
Examples
jshell> Map.of()
$12 ==> {}
jshell> Map.of("key1", "value1", "key2", "value2")
$13 ==> {key1=value1, key2=value2}
| created scratch variable $13 : Map<String,String>
Characteristics of Collections Static Factory Methods Common characteristics of these static Factory Methods for Lists, Sets, and Maps are:
Structurally Immutable: UnsupportedOperationException is thrown, although the elements themselves are immutable.
jshell> Set<String> immutableSet = Set.of("one","two","three")
immutableSet ==> [three, two, one]
| created variable immutableSet : Set<String>
jshell> immutableSet.add("four")
| java.lang.UnsupportedOperationException thrown:
No Nulls: NullPointerException thrown.
jshell> List<Object> notNullList = List.of(null)
| Warning:
| non-varargs call of varargs method with inexact argument type for last parameter;
| cast to java.lang.Object for a varargs call
| cast to java.lang.Object[] for a non-varargs call and to suppress this warning
| List<Object> notNullList = List.of(null);
| ^--^
| java.lang.NullPointerException thrown:
| at List.of (List.java:1030)
| at (#10:1)
Serialized – Serialized if elements are Serializable.
List-Specific Characteristics
Order – Order is maintained the same as elements input
jshell> List<String> immutableList = List.of("one","two","three")
immutableList ==> [one, two, three]
| created variable immutableList : List<String>
Set Specific Characteristics
Reject Duplicates – The Set will also reject duplicates at creation time with an IllegalArgumentException:
jshell> Set.of("one","one")
| java.lang.IllegalArgumentException thrown: duplicate element: one
Map Specific Characteristics
Reject Duplicate Keys – The Map will reject duplicate keys with IllegalArgumentException –
jshell> Map.of("KeyOne", "one", "KeyOne", "two")
| java.lang.IllegalArgumentException thrown: duplicate key: KeyOne
| at ImmutableCollections$MapN.<init> (ImmutableCollections.java:680)
| at Map.of (Map.java:1326)
| at (#1:1)
Iteration is also not guaranteed
These are useful and quick methods for creating immutable collections, and JShell provides a good testing ground to learn about the new methods and their associated characteristics.
Comments