What is the purpose behind the static final field in the Java – collections class?
The collections class has three static final fields named empty_ LIST,EMPTY_ Map and empty_ SET. They are all interface references and they are final What is their purpose?
Solution
The goal is that you do not need to construct new instances of immutable null data structures You can simply reuse existing These fields were introduced before generics For generics, you want to use accessor methods because they are type - safe in a generic way That is, not collections EMPTY_ Set you want to use collections emptySet(). A field cannot declare a type parameter, but a method can
This is an example of the use of empty sets
Suppose you have a function that returns the sum of a list of integers. You want to test that when you pass an empty list, it returns 0 The test looks 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 haven't thought of another example