Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose behind the static final fields in the Collections class?

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?

like image 613
user3516726 Avatar asked Nov 26 '25 20:11

user3516726


2 Answers

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&lt;String&gt; 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,

like image 84
Anders R. Bystrup Avatar answered Nov 28 '25 09:11

Anders R. Bystrup


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.

like image 31
Christian Hujer Avatar answered Nov 28 '25 08:11

Christian Hujer