Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

In this short tutorial, we’ll illustrate the difference between Collections.emptyList() and a new list instance.

2. Immutability

The core difference between java.util.Collections.emptyList() and a new list e.g. new ArrayList<>() is immutability.

Collections.emptyList() returns a list (java.util.Collections.EmptyList) that can’t be modified.

When creating a new list instance you can modify it depending on the implementation:

@Test
public void givenArrayList_whenAddingElement_addsNewElement() {	 	 
    List<String> mutableList = new ArrayList<>();	 	 
    mutableList.add("test");	 	 
 
    assertEquals(mutableList.size(), 1);	 	 
    assertEquals(mutableList.get(0), "test");	 	 
}
	 	 
@Test(expected = UnsupportedOperationException.class)	 	 
public void givenCollectionsEmptyList_whenAdding_throwsException() {	 	 
    List<String> immutableList = Collections.emptyList();	 	 
    immutableList.add("test");	 	 
}

3. Object Creation

Collection.emptyList() creates a new empty list instance only once, as shown in source code:

public static final List EMPTY_LIST = new EmptyList<>();

public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}

4. Readability

When you want to explicitly create an empty list, then Collections.emptyList() expressed the original intention better e.g. new ArrayList<>().

5. Conclusion

In this to the point article, we’ve focused on the differences between the Collections.emptyList() and a new list instance.

As always full source code is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.