简体   繁体   中英

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<>. However since Map is only an interface what class does the Map class reference actually point to?

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.

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-.

If you are interested on the value of any Map instance your code uses just print map.getClass() , here are a few examples:

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:

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

It returns an Immutable Map from the ImmutableCollections class. 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.

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. Immutable collections are more secure, are thread safe, and can be more efficient.

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