The release of Java 10 brings new static factory methods, specifically:
static <E> List<E> copyOf(Collection<? extends E> coll)
static <E> Set<E> copyOf(Collection<? extends E> coll)
static <K,V> Map<K,V> copyOf(Map<? extends K,? extends V> map)
Seeing as these methods allow us to copy Collection
s into different Collection
implementations, how do they compare and contrast to existing methods?
Just as List#of
, Set#of
, and Map#ofEntries
allow us to create unmodifiable implementations in Java 9, the copyOf
methods provide a convenient way to create unmodifiable implementations from existing Collection
s and Map
s (depending on the method, as Map#copyOf
accepts a Map
) in Java 10.
This allows us to easily create an unmodifiable Set<E>
from a List<E>
and vice versa.
Though, these methods bring a few caveats (quoting the documentation of java.util.List
):
- They are unmodifiable. Elements cannot be added, removed, or replaced. Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown. However, if the contained elements are themselves mutable, this may cause the List's contents to appear to change.
- They disallow null elements. Attempts to create them with null elements result in NullPointerException.
- They are serializable if all elements are serializable.
- The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.
- They are value-based. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones. Therefore, identity-sensitive operations on these instances (reference equality (==), identity hash code, and synchronization) are unreliable and should be avoided.
- They are serialized as specified on the Serialized Form page.
For the caveats of Set#copyOf
and Map#copyOf
, refer to their documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With