Finally, after 3 years of waiting Java 9 has reached the world. This major release was delayed several times due to the integration of its famous modularization feature called “Project Jigsaw”. But besides that major feature, Java 9 contains several other minor improvements which make the life of a programmer easier but are not that popular.
Today, I would like to introduce the collection initializer feature.
From time to time everyone has to initialize a collection of something. The typical Java way to do this was not very elegant compared to other programming languages. The most common way was to create a new collection and afterwards adding all the elements to it.
There were a few other ways to initialize collections but none was as elegant as the new collection initializer feature. With Java 9 it is possible to do the initialization in one line as we know it from other languages.
One important thing to notice is that the new “of” method does not return one of the common list implementations like ArrayList. Instead, a new immutable list implementation is used, which is not available in the public API. This means you cannot add or remove an item in the list. Doing this will result in an UnsupportedOperationException.
newList.remove(0); // UnsupportedOperationException
newList.clear(); // UnsupportedOperationException
The “of” method can also be applied to the collection types Map and Set.
After so many years of waiting it was about time that we also got a simple way to initialize collections. There are some drawbacks, like immutability, but I think it was a reasonable decision to design it like that in regard to performance aspects.