Java 9 - Factory Methods
The goal of providing factory methods is to make it convenient to create instances of various collection types with a very small number of syntactical footprint. In JVM based languages like Groovy, collection literals have been one of our favorite syntactical features ever since:
Creating a list or a map like in the example above is syntactically very consice and short compared to the Java equivalent:
For all collection types except maps, Java comes with a work-around to reduce the syntactical clutter with
Arrays.asList (JavaDoc), however, instantiating a concrete
Map is still syntactically a bit of a pain. Another option was to use the instance initializer and an anonymous sub-class to call
put in the initializer:
However, besides this approach being rather weird to most developers, it can cause memory-leaks and it creates a new sub-class for every usage. That’s not quite optimal too.
Java 9 provides subtile API additions to make those ugly code pieces go away.
Collection API Additions
In Java 9, the
java.util.Map interfaces got extended with new
*.of factory methods:
It’s important to understand that
of factory methods guarantee to return immutable collections, so you can’t use the returned collections to add more elements or remove existing ones. The concrete return collection type is considered to be an implementation detail, so there shouldn’t be any explicit checks on those types.
The new factory methods come with overloaded
@SafeVarargs methods allowing for an unlimited number of arguments. Besides the varargs method interface, the interfaces come with fixed argument method interfaces for up to 10 arguments. The overloaded method variants have been introduced to avoid array allocation and garbage collection overhead that would be introduced by having variable argument method interfaces only. Code implementing an
of method might choose to return a collection implementation optimised based on the number of given arguments.
Map Factory Method
Map.of is special in regard of variable args as it can not provide a variable list of arguments in its
of method implementation due to the possibility of having completely different key/value types. It does, however, provide overloaded
of method implementations for up to ten map entries, alternating between key and value arguments. To make this more clear, here is the method interface for ten map entries:
In addition, the
java.util.Map interface does provide an alternative method,
ofEntries expecting pairs of
Map.Entry<K, V> instances. The new
Map.entry(K, V) convenience method introduced in Java 9 can be used to create entry pairs:
of implementation not shown so far is
Set.of which uses basically the same syntax as
In this article we have a look at yet another Java 9 feature: convenience factory methods. Java 9 comes with new ways to instantiate immutable collection types with a more convenient syntax at which we will have a look in this article.