The three interfaces List
, Set
, and Map
all gained the new overloaded .of
methods.
List< Integer > luckyNumbers = List.of( 7 , 11 , 42 ) ;
Set< DayOfWeek > weekend = Set.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) ;
Map< DayOfWeek , Employee > dutyRoster =
Map.of(
DayOfWeek.MONDAY , alice ,
DayOfWeek.TUESDAY , bob ,
DayOfWeek.WEDNESDAY , alice ,
DayOfWeek.THURSDAY , carol ,
DayOfWeek.FRIDAY , carol
)
;
Convenience
Being able to declare and populate a List
, Set
, or Map
in a single line of code is quite convenient. Short, elegant, clearly expresses the programmer’s intention.
Not modifiable
Frequently, such short collections of objects are intended to be read-only. Meaning, the programmer using the collection cannot add, delete, or replace any of the collected objects.
Be aware that the content inside the collected objects may or may not be mutable. That is outside the scope of the collection’s duties.
The Collections
utility class provided ways to make a collection unmodifiable, but you had to go out of your way to make use of this feature. And doing so meant more lines of code. The new .of
methods are simpler.
Optimization
Note that you get back an object of the interface rather than a class. So for example, List
rather than ArrayList
, Set
rather than HashSet
, Map
rather than HashMap
. You have no idea what concrete class is in use by the returned object. Nor do you care.
This means the Java team is free to optimize the concrete implementation, changing the code from one release to another. They may even choose at runtime to use different implementations depending on the count or type of your objects being collected.
For example, if your collected objects are of an enum
type, then the highly-optimized EnumSet
could be used behind the scene to fulfill your request for a Set.of
. Likewise, EnumMap
for Map.of
. See the Set
and Map
code at the top of this Answers as examples of enum
objects being collected and therefore eligible for this optimization.
This freedom to optimize has been discussed by Brian Goetz and others.