Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Collections.EMPTY_LIST wihout an UncheckedException?

Tags:

java

generics

Is there a Generics Friendly way of using Collection.EMPTY_LIST in my Java Program.

I know I could just declare one myself, but I'm just curious to know if there's a way in the JDK to do this.

Something like users = Collections<User>.EMPTY_LIST;

like image 793
Allain Lalonde Avatar asked Oct 03 '08 23:10

Allain Lalonde


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 collection emptyList?

The emptyList() method of Java Collections returns the list with no elements. This method is immutable. That is, we can not do any modifications after creating this method. Syntax: public static final <T> List<T> emptyList()

How do you initialize an empty collection in Java?

In this post, I will be sharing how to initialize empty collection in Java. The java. util. Collections class provide utility methods such as emptyList(), emptySet(), and emptyMap() and three different static final fields such as EMPTY_LIST, EMPTY_SET, and EMPTY_MAP for creating empty List, Set and Map.

What is the correct way of returning an empty collection?

Collections. emptyList() : method used to return an empty list. Collections. emptySet() : method used to return an empty set.


1 Answers

By doing the following:

List<User> users = Collections.emptyList();

The type of the returned list from Collections.emptyList(); will be inferred as a String due to the left-hand-side of the assignment. However, if you prefer to not have this inference, you can define it explicitly by doing the following:

List<User> users = Collections.<User>emptyList(); 

In this particular instance, this may appear as redundant to most people (in fact, I've seen very little code out in the wild that makes use of explicit type arguments), however for a method with the signature: void doStuff(List<String> users) it would be perfectly clean for one to invoke doStuff() with an explicit type argument as follows:

doStuff(Collections.<String>emptyList());
like image 137
Ryan Delucchi Avatar answered Sep 29 '22 20:09

Ryan Delucchi