tags:

views:

1397

answers:

3

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;

+10  A: 

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());
Ryan Delucchi
every time you write down an explicit type argument in a method, god kills a kitten ( i think it was josh bloch who said this )
Andreas Petersson
+1  A: 
List<User> users = Collections.emptyList();
Steve Kuo
+1  A: 

After creating the empty list, I would recommend storing it as a constant rather than creating a new one each time.

Also, there are performance benefits to using Collections.emptyList() versus new ArrayList(0), although the difference is probably small. The list returned by emptyList() is optimized to be an immutable empty list. For example, the size() method simply returns 0, rather than a field lookup or whatever ArrayList does.

Adam Crume