java.util.Collections.emptyMap() Method


Description

The emptyMap() method is used to get the empty map (immutable). This map is serializable.

Declaration

Following is the declaration for java.util.Collections.emptyMap() method.

public static final <K,V> Map<K,V> emptyMap()

Parameters

NA

Return Value

NA

Exception

NA

Example

The following example shows the usage of java.util.Collections.emptyMap()

package com.tutorialspoint;

import java.util.*;

public class CollectionsDemo {
   public static void main(String args[]) {
      
      // create an empty map    
      Map<String, String> emptymap = Collections.emptyMap();

      System.out.println("Created empty immutable map: "+emptymap); 

      // try to add elements
      emptymap.put("1","value");
   }    
}

Let us compile and run the above program, this will produce the following result.The map is immutable so adding elements will throw exception.

Created empty immutable map: {}
Exception in thread "main" java.lang.UnsupportedOperationException
java_util_collections.htm
Advertisements