tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Collections > Empty Collection

Empty Collection 

The following example shows how to create an empty collection. Using empty collections instead of assigning null avoids NullPointerException. The Collections class provides several type safe methods which return empty collections which are both immutable and Serializable.

  • Collections.emptyList()
  • Collections.emptySet()
  • Collections.emptyMap()
As these returned collection is immutable changing the state of it using methods such as add/set/put throws UnsupportedOperationException. It acts as a place holder until the actual collection is initialized.
 

File Name  :  
com/bethecoder/tutorials/utils/collections/EmptyCollection.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.collections;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class EmptyCollection {

  /**
   @param args
   */
  public static void main(String[] args) {

    //Empty list of Strings
    List<String> strList = Collections.<String>emptyList();
    print(strList);
    
    //Empty list of Booleans
    List<Boolean> boolList = Collections.<Boolean>emptyList();
    print(boolList);
    
    //Empty list of Employees
    List<Emplooyee> empList = Collections.<Emplooyee>emptyList();
    print(empList);
    
    //Empty Set of Employees
    Set<Emplooyee> empSet = Collections.<Emplooyee>emptySet();
    print(empSet);
    
    //Empty Map of Employees
    Map<String, Emplooyee> empMap = Collections.<String, Emplooyee>emptyMap();
    System.out.println(empMap + " size : " + empMap.size());
  }

  public static void print(Collection<?> collection) {
    System.out.println(collection + " size : " + collection.size());
  }
}

class Emplooyee {
  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}
   

It gives the following output,
[] size : 0
[] size : 0
[] size : 0
[] size : 0
{} size : 0



 
  


  
bl  br