Java - Empty Collections

When a collection is returned from a method, and if the collection to be returned is null , then it is always better to return an empty collection.
There are methods available in Collections class to return empty collection with respect to Map, List and Set.

public class Matrix<T>
{
    public static void main(String[] input1)
    {
        //Write code here
        Matrix<String> mt = new Matrix<String>();
        Collection<String> lstStr = mt.processColl(null);
    }
   
    public Collection<T> processColl(Collection<T> coll)
    {
        if(null == coll)
        {
                return Collections.emptyList();
                //return new ArrayList<String>();
        }
        return coll;
    }
}

In the above code, Collections.emptyList() returns an immutable list. So , the developer needs to ensure that the calling method should not modify the returned collection.
Since the returned collection is immutable, it provides a performance improvement over using a new instance of a Collection.

Technology: 

Search