Creating an empty, immutable, List

Starting with Java 9, you can use List.of() to create an empty, immutable, List instance with typed elements (if there were any):


import java.util.Collections;
import java.util.List;

import org.junit.jupiter.api.Test;

public class EmptyListsTest {

    //Java 9+
    @Test
    public void listOf() {
        var emptyList = List.<String>of();
        assertTrue(emptyList.isEmpty());
    }
}    

Prior to Java 9, you would have to use Collections.emptyList() to create an empty, immutable, List:

    //Java 5+
    @Test
    public void emptyList() {
        var emptyList = Collections.<String>emptyList();
        assertTrue(emptyList.isEmpty());
    }

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments
License