简体   繁体   中英

Java: Map.of<"k1", "v1"> vs Collections.singletonMap("k1", "v1")

Are there any differences between Map.of("key", "value") and Collections.singletonMap("key", "value") ?

Are there any practices on which one is to be preferred over another if I just need to store one mapping for Java 9 and above?

Map.of

Map.of can only be used in Java 9 and above. It can be used to store 0 to 10 key-value pairs. See https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#of-- and following. See also https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#immutable :

The Map.of() and Map.ofEntries() static factory methods provide a convenient way to create immutable maps. The Map instances created by these methods have the following characteristics:

  • They are structurally immutable. Keys and values cannot be added, removed, or updated. Calling any mutator method will always cause UnsupportedOperationException to be thrown. However, if the contained keys or values are themselves mutable, this may cause the Map to behave inconsistently or its contents to appear to change.
  • They disallow null keys and values. Attempts to create them with null keys or values result in NullPointerException.
  • They are serializable if all keys and values are serializable.
  • They reject duplicate keys at creation time. Duplicate keys passed to a static factory method result in IllegalArgumentException.
  • The iteration order of mappings is unspecified and is subject to change. They are value-based. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones. Therefore, identity-sensitive operations on these instances (reference equality (==), identity hash code, and synchronization) are unreliable and should be avoided. They are serialized as specified on the Serialized Form page.

Similarily, there is List.of and Set.of .

Collections.singletonMap

Collections.singletonMap is available since Java 1.3. It can only be used to store one key-value pair. See https://docs.oracle.com/javase/9/docs/api/java/util/Collections.html#singletonMap-KV- .

In general, singletons always contain exactly one value. A singleton class is one that has exactly one instance. A singleton map has exactly one mapping, a singleton list has exactly one element and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM