Why do we have immutable empty map?

collections, dictionary, immutability, java

Solution

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.

Problem

``` /** * 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?

Original source

Related problems