Home  >  Core Java

Collections.emptyList in Java

By Arvind Rai, February 04, 2022
Find the Java doc of Collections.emptyList method.
static final <T> List<T> emptyList() 
1. The 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.java
package 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;
    }
} 
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.

Reference

Java Collections
POSTED BY
ARVIND RAI
ARVIND RAI










©2022 concretepage.com | Privacy Policy | Contact Us