Class CollectionFactoryExamples
java.lang.Object
net.jrodolfo.java_evolution.java09.CollectionFactoryExamples
Demonstrates collection factory methods introduced in Java 9.
Before Java 9, creating a small read-only collection usually required several steps: create a mutable collection, populate it, and wrap it with an unmodifiable view. That made simple constants and test data noisier than the values being represented.
List.of(Object[]), Set.of(Object[]), and
Map.of(Object, Object) solve that problem for small collections.
They are compact, reject null, reject duplicate set elements or map
keys, and return collections that cannot be mutated. The JDK can also use
specialized internal implementations for small immutable collections, which
is one reason these factories are preferable to hand-built wrappers for
constants and examples.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionCreates an immutable set.Creates an immutable list.Shows that factory collections rejectnull.Shows thatMap.of(Object, Object, Object, Object)rejects duplicate keys.Creates an immutable map.Shows thatSet.of(Object[])rejects duplicates.
-
Constructor Details
-
CollectionFactoryExamples
public CollectionFactoryExamples()
-
-
Method Details
-
languageFeatures
Creates an immutable list.- Returns:
- a list created with
List.of(Object[])
-
languageFeatureCategories
Creates an immutable set.- Returns:
- a set created with
Set.of(Object[])
-
releaseNamesByVersion
Creates an immutable map.- Returns:
- a map created with
Map.of(Object, Object, Object, Object)
-
listWithNullValue
Shows that factory collections rejectnull.- Returns:
- never returns because
List.of(Object[])throws
-
setWithDuplicateValues
Shows thatSet.of(Object[])rejects duplicates.- Returns:
- never returns because the set contains duplicate values
-
mapWithDuplicateKeys
Shows thatMap.of(Object, Object, Object, Object)rejects duplicate keys.- Returns:
- never returns because the map contains duplicate keys
-