简体   繁体   English

Map.of() 与 Collections.emptyMap()

[英]Map.of() vs. Collections.emptyMap()

有没有之间的差异Map.of()Collections.emptyMap()之间List.of()Collections.emptyList()之间Set.of()Collections.emptySet()

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.是的,甚至还有的行为,而不是通过返回的集合彼此只是技术上的差异emptyXyz在工厂方法Collections类和新of在接口(引入工厂方法MapListSet )与JDK 9,如果这些与调用没有争论。

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).有关不同的是,由新返回集合of工厂方法禁止null键和值(如API文档中指出,在列表设置地图接口)。 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 . Collections.emptyList().contains(null)将返回 false,而List.of().contains(null)将抛出NullPointerException

Collection.emptyMap().getOrDefault(null, V) will return V , while Map.of().getOrDefault(null, V) will throw a NullPointerException . Collection.emptyMap().getOrDefault(null, V)将返回V ,而Map.of().getOrDefault(null, V)将抛出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:正如目前在 Oracle 的 JDK 9 中实现的那样,至少由新工厂方法返回的集合上的以下方法将抛出NullPointerException s,但行为“正常”(就像最初设计和指定集合类以支持空键和值一样) ) 使用Collections类中的旧工厂方法:

  • List.of().contains(null);
  • Set.of().contains(null);
  • Map.of().containsKey(null);
  • Map.of().containsValue(null);
  • Map.of().getOrDefault(null, <any>);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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