Collections.emptyList in Java
February 04, 2022
Find the Java doc of Collections.emptyList
method.
static final <T> List<T> emptyList()
emptyList
returns an immutable empty list.
2. In immutable list, we cannot add or remove elements.
3. The use of empty list is that if our method is returning empty list, create it by
Collections.emptyList
method.
4. Immutable empty list performance is faster than
new ArrayList()
.
5. The
emptyList
is used as following.
List<String> list = Collections.emptyList();
Example
CollectionsEmpty.javapackage com.concretepage.util; import java.util.Collections; import java.util.List; public class CollectionsEmpty { int row = getRowFromDB(); //immutable empty List public List<String> getDataInList(){ List<String> list = null; if (row == 0) { list = Collections.emptyList(); } return list; } private int getRowFromDB() { int cnt = 0; //access DB to calculate rows //returns DB rows return cnt; } }