The Collections class has three static final fields called EMPTY_LIST, EMPTY_MAP and EMPTY_SET. They are all interface references, and they are final. So what is their purpose?
Quoting from the JDK7 source, eg.:
/**
* 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;
}
That should answer your question. They're even mentioned in the Collections JavaDoc as being immutable, thus safe to have only one of, and thus static.
Cheers,
The purpose is that you don't need to construct new instances of immutable empty datastructures. You can simply reuse the existing ones. These fields had been introduced before Generics. With Generics you want to use the accessor methods instead because they are type-safe in a Generics way. I.e. instead of Collections.EMPTY_SET you want to use Collections.emptySet(). Fields cannot declare type parameters, but methods can.
Here's an example where an empty collection comes in handy.
Let's assume you have a function which returns the sum of a List of Integers, and you want to test that when you pass the empty list, it returns 0. 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 test classes, so I couldn't think of another example yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With