Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What differentiates List#copyOf, Set#copyOf, and Map#copyOf from traditional methods?

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 Collections into different Collection implementations, how do they compare and contrast to existing methods?

like image 992
Jacob G. Avatar asked Jan 28 '23 13:01

Jacob G.


1 Answers

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 Collections and Maps (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.

like image 72
Jacob G. Avatar answered Feb 06 '23 14:02

Jacob G.