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;
The emptyList() method of Java Collections class is used to get a List that has no elements. These empty list are immutable in nature.
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()
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.
Collections. emptyList() : method used to return an empty list. Collections. emptySet() : method used to return an empty set.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With