Skip to main content

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:
Answer 1:

  myCrazyBook.setTitles(new ArrayList()); 

-WARRNING - ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized

Ok changing to:

  myCrazyBook.setTitles(new ArrayList<String>());   

WTF ? the problem in this answer is not small one :
- you are creating empty ArrayList which basiclly is not needed. ( what if you are in a loop 1000+ empty ArrayLists ? )

Answer 2.

   myCrazyBook.setTitles(Collections.EMPTY_LIST);

-WARNING : Type safety: The expression of type List needs unchecked conversion to conform to List<String>, because the EMPTY_LIST is raw type, which was heavily used before Java 1.5.
The definition of this list is :

    /**

     * The empty list (immutable).  This list is serializable.

     *

     * @see #emptyList()

     */

    public static final List EMPTY_LIST = new EmptyList();

So you see it is not ArrayList or LinkedList or MyCrazyCustomListWhichIUseEveryWhereList.

Answer 3:
Eclipse will tell you this answer : Replace with Collections.emptyList();

      myCrazyBook.setTitles(Collections.emptyList());

COMPILE TIME ERROR: why ? because emptyList invoked like that means List of Objects not List of String. The other thing is that you cannot cast to List<String> because you cannot cast List<Object>  to List<String>.

Answer 4:
You know that there is Collections.emptyList() AND YOU KNOW THAT IT RETURNS List<T>
so your answer is:

            Book myCrazyBook=new Book();

            List<String> titles = Collections.emptyList();

            myCrazyBook.setTitles(titles);

           

And this will work WITHOUT any WARNINGS or ERRORS. The type of the List is taken from the type of the variable that you are trying to assign to.
Of course why you need this local variable ? I want to remove it it is not needed and used, but if you remove it you are in Answer 3. So what can you do ?

Answer 5: The right but strange looking answer.

            Book myCrazyBook=new Book();

            myCrazyBook.setTitles(Collections.<String>emptyList());

Yes this is not a joke there is a dot (.) then the generic type before the method name. This compiles, runs, no warnings thats the real way.
It is a little strange that most people dont know this aspect of generics in Java even I didn't know it, I was thinking that you cannot pass a generic type like this but as it looks you can.

So if you have some static method like this one:

public class Main{

      public static <G> List<G> someGreatMethod(){

            List<G> gList= new ArrayList<G>();

            return gList;

      }

}

you can invoke it with Main.<String>someGreatMethod(); for example.

Comments

Unknown said…
That was very new for me and of course very strange. Thanks it was very clear.
jNayden said…
Very strange indeed :)
Unknown said…
Wow, strange but neat! I didn't know this at all and always used the method proposed in answer 4.
Stilgar said…
I am aware that the article deals with the language syntax but I must point out that passing emptyList to a class that has a public getter that exposes List is a bad practice. The consumer does not know that the implementation is an emptyList and will throw an exception when the add method is called. This makes using emptyList inappropriate. The example would be OK if instead of List the Book class exposed Iterable
Unknown said…
Didn't know that. Thanks for posting it.
jNayden said…
Stilgar : Agree I was needing only the seter for that example, I agree about the getter. :) Shame on eclipse it generates everything :DD kidding :D
Sir Moon said…
"passing emptyList to a class that has a public getter that exposes List is a bad practice"

i have to correct this nonsense. implementations of List are not required to support adding elements, so clients should always be aware that the add method may throw. emptyList() is no worse than unmodifiableList().

Popular posts from this blog

Use Multiple JVM versions on Mac OS and Linux

Linux Download multiple Java versions and put them into /opt/ If you already have some JDK from ubuntu repo or etc not a big deal, just fix the paths bellow Register them as alternatives sudo update-alternatives --install /usr/bin/java java /opt/java-8-oracle/bin/java 1081 sudo update-alternatives --install /usr/bin/java java /opt/sap-machine-jdk-11.0.3/bin/java 1080 Edit your ~/.bashrc file alias java11='sudo update-alternatives --set java /opt/sapmachine-jdk-11.0.3/bin/java;export JAVA_HOME=/opt/sapmachine-jdk-11.0.3/' alias java8='sudo update-alternatives --set java /opt/java-8-oracle/bin/java;export JAVA_HOME=/usr/lib/java-8-oracle/' SAVE and start a new bash terminal execute java8 to use java8 java11 to use java11 the latest version you have set stays as system wide, but the JAVA_HOME is not :( you can put java8 or java11 as a last line in the bashrc but since it is sudo it will always require password when start and is not gr...

Hibernate Generic DAO.

When you use Hibernate and DAO pattern it is a good idea to use a Generic Base Dao. The fallowing code snippet contains GenericDAO that is a base class for all my DAO classes. This GenericDAO uses HibernateDaoSupport from Spring for its implementation if you want you can use JpaDaoSupport or JdbcDaoSupport in your projects. My Generic DAO interface looks like this : package org.joke.myproject.dao.base; import java.io.Serializable; import java.util.List; /** * @author Naiden Gochev * @param <E> * @param <PK> */ public interface GenericDao<E,PK  extends Serializable> {     PK save(E newInstance);     void update(E transientObject);     void saveOrUpdate(E transientObject);     void delete(E persistentObject);     E findById(PK id);     List<E> findAll();     List<E> f...

Patching a Maven library with your custom class.

Sometimes you use a library that has a bug. Or maybe it doesn’t has a bug but you want to change something. Of course if it is an open source you can get the sources… build them … with your change and so on. However this first takes a lot of time and second you need the sources. What you usually want .. is to just replace one class.. or few classes with something custom… maybe add a line .. or remove a line and so on. Yesterday… I had an issue with jboss-logging. The version I was using was 3.2.0Beta1 and it turns out that using this version and log4j2 2.0 final basically meant that no log is send to log4j2. The reason was a null pointer exception that was catched in jboss logging class called Log4j2Logger. The bug I submitted is here https://issues.jboss.org/browse/JBLOGGING-107 and it was fixed at the same day. However I will use it as an example since I didn’t knew when this will be fixed.. and I didn’t want to wait till it is fixed. So I was thinking what I want.. to take the j...