Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we have immutable empty map?

/**
 * Returns the empty map (immutable).  This map is serializable.
 *
 * <p>This example illustrates the type-safe way to obtain an empty set:
 * <pre>
 *     Map&lt;String, Date&gt; s = Collections.emptyMap();
 * </pre>
 * Implementation note:  Implementations of this method need not
 * create a separate <tt>Map</tt> object for each call.   Using this
 * method is likely to have comparable cost to using the like-named
 * field.  (Unlike this method, the field does not provide type safety.)
 *
 * @see #EMPTY_MAP
 * @since 1.5
 */
@SuppressWarnings("unchecked")
public static final <K,V> Map<K,V> emptyMap() {
    return (Map<K,V>) EMPTY_MAP;
}

Above function returns an immutable empty map.

public static final Map EMPTY_MAP = new EmptyMap<>();

EmptyMap class is as follows

/**
 * @serial include
 */
private static class EmptyMap<K,V>
    extends AbstractMap<K,V>
    implements Serializable
{
    private static final long serialVersionUID = 6428348081105594320L;

    public int size()                          {return 0;}
    public boolean isEmpty()                   {return true;}
    public boolean containsKey(Object key)     {return false;}
    public boolean containsValue(Object value) {return false;}
    public V get(Object key)                   {return null;}
    public Set<K> keySet()                     {return emptySet();}
    public Collection<V> values()              {return emptySet();}
    public Set<Map.Entry<K,V>> entrySet()      {return emptySet();}

    public boolean equals(Object o) {
        return (o instanceof Map) && ((Map<?,?>)o).isEmpty();
    }

    public int hashCode()                      {return 0;}

    // Preserves singleton property
    private Object readResolve() {
        return EMPTY_MAP;
    }
}

What is the use of such Class and utility method? I tried

Map myMap = Collections.emptyMap();
myMap.put("Name","John");

and I get Exception in thread "main" java.lang.UnsupportedOperationException because collection being immutable does not support modification. So whats the use of such data structure?

like image 548
Aniket Thakur Avatar asked Aug 02 '13 08:08

Aniket Thakur


People also ask

Why is my Map immutable?

ImmutableMap, as suggested by the name, is a type of Map which is immutable. It means that the content of the map are fixed or constant after declaration, that is, they are read-only. If any attempt made to add, delete and update elements in the Map, UnsupportedOperationException is thrown.

What is the use of empty Map?

The emptyMap and the immutableMap can be used to create objects, that are immutable. emptyMap is the initial point. Each time an element is added the map itself is replaced by a map containing the old element and the new elements. The point is, that accesses to the object are safe.

Why key in HashMap is immutable?

Immutabiility is required, in order to prevent changes on fields used to calculate hashCode() because if key object return different hashCode during insertion and retrieval than it won't be possible to get object from HashMap.

What is the use of empty Map in Java?

The emptyMap() method of Java Collections is a method that is used to return an empty map such that we can not change the data in map IE it is immutable. where, key is the key element. value is the value element.


2 Answers

What is the use of such Class and utility method?

If you're returning a Map result, it's often useful for it to be immutable... for example, you can create an immutable map which wraps your own "real" data rather than having to either create a full copy, or trust the caller not to mutate it.

Also, if you're returning a Map result which is empty, it's convenient not to have to create a new object each time - every empty map is equivalent to every other empty map, so it's fine to use a single instance.

like image 131
Jon Skeet Avatar answered Oct 18 '22 13:10

Jon Skeet


This helps to implement Null Object design pattern http://en.wikipedia.org/wiki/Null_Object_pattern, that is returning an empty map instead of null

like image 37
Evgeniy Dorofeev Avatar answered Oct 18 '22 13:10

Evgeniy Dorofeev