Home  >  Core Java

Example of Collections.emptyList in Java

By Arvind Rai, May 26, 2013
In Java Collections.emptyList is used to get empty and immutable List object. As this is immutable so we cannot add element in this list. The use of empty list is that if our method is returning list or empty list and at that time sending immutable empty list ensures that it cannot be changed. Collections.emptyList provides a type safe view not to add element. Its performance is faster than new ArrayList().
package com.concretepage.util;
import java.util.Collections;
import java.util.List;
public class CollectionsEmptyDemo {
    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;
For the example suppose we are returning data from database and if no rows fetched then instead of returning null, we can return immutable List.

©2021 concretepage.com | Privacy Policy | Contact Us