Skip to main content

Posts

Showing posts from July, 2010

Using of Collections.emptyList() the right way in Java 1.5+

It is little strange that no one really uses emptyList like he should in Java. So this is small post showing how to use the emptyList method in the Collections class. Question: How to create an empty list ? lets assume that we have a class Book with multiple titles. So the class in our examples will be: import java.util.List; public class Book {       private List<String> titles ;       public void setTitles(List<String> titles) {             this . titles = titles;       }       public List<String> getTitles() {             return titles ;       } } Lets say that in our snippet we have something like :   Book myCrazyBook= new Book(); and we want to assign an empty list to the titles in this book. This is a common scenario if you want to set something to be emptyList in specific case instead of null. So of course your first try will be something like: