Home > Mobile >  What class instance does Map.of() return?
What class instance does Map.of() return?

Time:11-02

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?

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related