Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map.of() vs. Collections.emptyMap()

Is there a difference between Map.of() and Collections.emptyMap(), between List.of() and Collections.emptyList() and between Set.of() and Collections.emptySet()?

like image 760
msayag Avatar asked Sep 25 '17 12:09

msayag


People also ask

What is collections emptyMap () 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. Syntax: public static final <Key,Value> Map<Key,Value> emptyMap() where, key is the key element. value is the value element.

Are collections emptyMap immutable?

The map is immutable so adding elements will throw exception.

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.

How do you clear a map in Java?

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.


1 Answers

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 NullPointerExceptions, 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>);
like image 200
jarnbjo Avatar answered Oct 01 '22 05:10

jarnbjo