What is the point of overloaded Convenience Factory Methods for Collections in Java 9

From the JEP docs itself –

Description

These will include varargs overloads, so that there is no fixed limit
on the collection size. However, the collection instances so created
may be tuned for smaller sizes. Special-case APIs (fixed-argument
overloads) for up to ten of elements will be provided. While this
introduces some clutter in the API, it avoids array allocation,
initialization, and garbage collection overhead that is incurred by
varargs calls.
Significantly, the source code of the call site is the same regardless of whether a fixed-arg or varargs overload is called.


Edit – To add motivation and as already mentioned in the comments by @CKing too :

Non-Goals

It is not a goal to support high-performance, scalable collections
with arbitrary numbers of elements. The focus is on small collections.

Motivation

Creating a small, unmodifiable collection (say, a set) involves constructing it, storing it in a local variable, and invoking add() on it several times, and then wrapping it.

Set<String> set = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("a", "b", "c")));

The Java 8 Stream API can be used to construct small collections, by combining stream factory methods and collectors.

// Java 8
Set<String> set1 = Collections.unmodifiableSet(Stream.of("a", "b", "c").collect(Collectors.toSet()));

Much of the benefit of collection literals can be gained by providing library APIs for creating small collection instances, at significantly reduced cost and risk compared to changing the language. For example, the code to create a small Set instance might look like this:

// Java 9 
Set set2 = Set.of("a", "b", "c");

Leave a Comment