Is there a difference between Map.of()
and Collections.emptyMap()
, between List.of()
and Collections.emptyList()
and between Set.of()
and Collections.emptySet()
?
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. Syntax: public static final <Key,Value> Map<Key,Value> emptyMap() where, key is the key element. value is the value element.
The map is immutable so adding elements will throw exception.
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.
clear() method in Java is used to clear and remove all of the elements or mappings from a specified HashMap. Parameters: The method does not accept any parameters. Return Value: The method does not return any value.
Yes, there are even behavioral and not just technical differences between the collections returned by the emptyXyz
factory methods in the Collections
class and the new of
factory methods introduced in the interfaces (Map
, List
, Set
) with JDK 9, if these are invoked with no arguments.
The relevant difference is that the collections returned by the new of
factory methods disallow null
keys and values (as pointed out in the API documentation in the List, Set and Map interfaces). This might sound irrelvant for empty collections, but even if it is not quite clearly documented, even the accessor methods in the new collection implementations check for null values.
Some examples of the differences:
Collections.emptyList().contains(null)
will return false, while List.of().contains(null)
will throw a NullPointerException
.
Collection.emptyMap().getOrDefault(null, V)
will return V
, while Map.of().getOrDefault(null, V)
will throw a NullPointerException
.
As currently implemented in Oracle's JDK 9, at least the following methods on the collections returned by the new factory methods will throw NullPointerException
s, but behave 'sanely' (as in how the collection classes were originally designed and specified to support null keys and values) using the old factory methods in the Collections
class:
List.of().contains(null);
Set.of().contains(null);
Map.of().containsKey(null);
Map.of().containsValue(null);
Map.of().getOrDefault(null, <any>);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With