Java 9: Convenience Factory Methods for Collections

If you are following the feature set to be included in Java 9, you may have noticed JEP 269: Convenience Factory Methods for Collections. According to the proposal, this feature is to “provide static factory methods on the collection interfaces that will create compact, unmodifiable collection instances. The API is deliberately kept minimal.”

The expert group discusses alternatives, and explains in particular : “The Google Guava libraries have a rich set of utilities for creating immutable collections, including a builder pattern, and for creating a wide variety of mutable collections. The Guava libraries are very useful and general but are perhaps overkill for inclusion into the Java SE Platform.” However, I would argue that if Guava is “very useful” and “general”, that makes it completely appropriate for inclusion in Java SE proper. But that’s just my opinion!

If you look at the Java 9 API for Set, one thing that may jump out at you is the plethora of “.of()” methods, such as this .of() method with 10 arguments. The argument for this (!) is that “While this introduces some clutter in the API, it avoids array allocation, initialization, and garbage collection overhead that is incurred by varargs calls.” So here is a real-world instance where there was an evaluation between clarity of API design vs performance considerations, and in this case, the performance considerations won.

Without any further ado, here is an example of the new API:

Set strings = Set.of("a", "b");

Reading the Set javadocs with all the .of() methods is a little confusing at first (as to why they did that) but the nice part is that the code as used reads quite nicely.

Enjoy your tidy new Sets!

Leave a comment

Filed under Java 9

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s