Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collections.emptyList() instead of null check?

Tags:

If I have a rarely used collection in some class which may be instantiated many times, I may sometimes resort to the following "idiom" in order to save unnecessary object creations:

List<Object> list = null;  void add(Object object) {     if (list == null)         list = new ArrayList<Object>();      list.add(object); }  // somewhere else if (list != null)     for (Object object : list)          ; 

Now I was wondering if I couldn't eliminate those null checks using Collections.emptyList(), however then I would have to alter the if check in add() like so:

if (list == Collections.<Object>emptyList())     list = new ArrayList<Object>(); 

Is there a better way to handle this other than just allocating a new empty collection every time?

EDIT: just to be clear, I would like to use Collections.emptyList(), but the above check in add() is really really ugly... I was wondering if there's a better way to do it or even a whole other way of handling this.

like image 266
Philip Kamenarsky Avatar asked Jul 01 '11 10:07

Philip Kamenarsky


People also ask

When would you use collections emptyList?

The emptyList() method of Java Collections class is used to get a List that has no elements. These empty list are immutable in nature.

What is the difference between collections emptyList () and creating new instance of collection?

emptyList is immutable so there is a difference between the two versions so you have to consider users of the returned value. Returning new ArrayList<Foo> always creates a new instance of the object so it has a very slight extra cost associated with it which may give you a reason to use Collections.

Does collection isEmpty check for null?

You can use the apache commons library in your project, you can use the method CollectionUtils. isEmpty . This returns true if the collection is null or empty.

How do I check if a collection is empty?

The standard solution to check if a Java Collection is empty is calling the isEmpty() method on the corresponding collection. It returns true if the collection contains no elements. The following solution provides the custom implementation of isEmpty() and isNotEmpty() methods, that handles null input gracefully.


2 Answers

in order to save unnecessary object creations

That's a really bad idea which will litter your code with == null checks and other handling of corner cases (and presumably end up in null pointer exceptions anyway)!

Now I was wondering if I couldn't eliminate those null checks using Collections.emptyList()

No, not really. emptyList() returns an empty list. You could do

if (list.equals(Collections.<Object>emptyList())) 

but that will still throw a NullPointerException if list == null, so it's still not what you're after.

My recommendation: Always initialize the list to new ArrayList<Object>, or, if you for instance want to return an empty list from a method, use Collections.emptyList() instead. (This returns the same instance every time, so no unnecessary object creation there either.)

And then use .isEmpty() to check if a collection is empty or not.

like image 173
aioobe Avatar answered Sep 25 '22 00:09

aioobe


The suggested answers are absolutely correct, just small tip - in Java 8 you can use the new Optional class to handle the case where the list instance is null, in a more functional approach.

For example, something like this:

public static List<String> addElement(List<String> list, String toAdd) {        List<String> newList = Optional.ofNullable(list).orElse(new ArrayList<>());        newList.add(toAdd);        return newList; } 

Following a tip in the comments, it's better to replace new ArrayList<>() with Collections.emptyList() in order to prevent the creation of a new instance of an empty ArrayList

public static List<String> addElement(List<String> list, String toAdd) {    List<String> newList = Optional.ofNullable(list).orElse(Collections.emptyList());    newList.add(toAdd);    return newList; } 
like image 20
Johnny Avatar answered Sep 23 '22 00:09

Johnny