What is the purpose of static final fields in the Collections class?
The goal is that you don't need to create new instances of immutable empty data structures. You can simply reuse existing ones. These fields were introduced before Generics. In Generics, you want to use accessor methods because they are type safe in Generics mode. That is, instead Collections.EMPTY_SET
you want to use Collections.emptySet()
. Fields cannot declare type parameters, but methods can.
Here's an example when you need an empty collection.
Suppose you have a function that returns the sum of a list of integers, and you want to test that it returns 0 when passed in an empty list. The test would look like this:
public class IntSumTest {
@Test
public void givenEmptyList_whenSumming_thenReturnsZero() {
assertEquals(0, sum(Collections.emptyList());
}
}
I rarely use empty collections outside of test classes, so I couldn't come up with another example yet.
source to share
Quoting from the JDK7 source, for example:
/**
* Returns the empty set (immutable). This set is serializable.
* Unlike the like-named field, this method is parameterized.
*
* <p>This example illustrates the type-safe way to obtain an empty set:
* <pre>
* Set<String> s = Collections.emptySet();
* </pre>
* Implementation note: Implementations of this method need not
* create a separate <tt>Set</tt> object for each call. Using this
* method is likely to have comparable cost to using the like-named
* field. (Unlike this method, the field does not provide type safety.)
*
* @see #EMPTY_SET
* @since 1.5
*/
@SuppressWarnings("unchecked")
public static final <T> Set<T> emptySet() {
return (Set<T>) EMPTY_SET;
}
This should answer your question. They are even referred to in the Collections JavaDoc as immutable, so it is safe to only have one, and therefore static
.
Greetings,
source to share
The best practice API will never return a collection return method null
. If there are no items to return, an empty collection should be returned.
Also, when calling into some API that does not carry null
s, you may have a reference to <possibly> null
that you have to translate to one that is always non-zero.
In all such cases, it is best if the overall performance of the application uses a single instance, which is an immutable, empty collection, rather than time and memory, with a new one created each time. The JDK provides you with such singletons.
source to share