简体   繁体   English

Map.of() 返回什么类实例?

[英]What class instance does Map.of() return?

I'm currently learning about collections and I noticed that the factory method Map.of returns an object of type Map<>.我目前正在学习集合,我注意到工厂方法 Map.of 返回一个 Map<> 类型的对象。 However since Map is only an interface what class does the Map class reference actually point to?但是,由于 Map 只是一个接口,Map 类引用实际上指向什么类?

It is not guaranteed to return an instance of any specific class, so your code should not depend on that.不能保证返回任何特定类的实例,因此您的代码不应依赖于此。 However, for the sake of learning, OpenJDK 11 returns an instance of ImmutableCollections.Map1 , one of several lightweight special-purpose classes written specifically for the Map.of overloads.但是,为了学习起见,OpenJDK 11 返回了ImmutableCollections.Map1一个实例,它是专门为Map.of重载编写的几个轻量级专用类Map.of

It won't be the same depending on the Map size and you should not rely on the value returned as per the answer by @chrylis -cautiouslyoptimistic-.根据地图大小,它不会相同,您不应该依赖根据@chrylis -cautiouslyoptimistic- 的答案返回的值。

If you are interested on the value of any Map instance your code uses just print map.getClass() , here are a few examples:如果您对您的代码仅使用 print map.getClass()的任何Map实例的值感兴趣,以下是一些示例:

System.out.println(Map.of().getClass());
System.out.println(Map.of(1,2).getClass());
System.out.println(Map.of(1,2,3,4,5,6).getClass());

Which (in JDK17) prints:其中(在 JDK17 中)打印:

class java.util.ImmutableCollections$MapN
class java.util.ImmutableCollections$Map1
class java.util.ImmutableCollections$MapN

It returns an Immutable Map from the ImmutableCollections class.它从 ImmutableCollections 类返回一个不可变映射。 This class is not part of the public API, but it extends AbstractMap which supplies implementations for all of the basic methods needed for a Map.此类不是公共 API 的一部分,但它扩展了 AbstractMap,后者提供 Map 所需的所有基本方法的实现。

The important takeaway is that the Map returned by Map.of() is immutable so you can't add to or change it after it is created.重要的一点是 Map.of() 返回的 Map 是不可变的,因此您无法在创建后添加或更改它。 Immutable collections are more secure, are thread safe, and can be more efficient.不可变集合更安全、线程安全且效率更高。

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

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