简体   繁体   中英

ImmutableMap.of vs Java Map.of

I have seen that ImmutableMap.of is used to create immutable map object. At the same time Java offers Map.of which creates immutable map as well. Is there any advantage of using ImmutableMap.of instead of Map.of from Java ?

Edit: I am not asking differences between map and immutable map. I am asking why some people prefer ImmutableMap.of instead of Map.of which also creates immutableMap.

A possible downside of Map.of is that it returns Map , which provides a lot of methods that are documented to throw UnsupportedOperationException in case the map is immutable - that may be considered a disadvantage in API design. There is no reliable way for code consuming Map s to know whether any of these will work.

There were good reasons for this decision, such as being able to take advantage of the existing codebase without breaking backwards compatibility. But this comes at the cost that the type system can't help with communicating whether a given method can accept (or requires) an immutable or a mutable map. That is left to documentation.

( guavas ImmutableMap also implements Map , but at least the unsupported methods are marked as deprecated. Arguably still not ideal, but... tradeoffs)

I assume you are talking about com.google.common.collect.ImmutableMap ? According to the javadoc , that has been in guava since 2.0, which is really old (I can only find the year 2010 for version 3.0 , so 2.0 is before that).

Map.of was only introduced with java 9, which was released in September 2017 . That means that only the first option was available before java 9, but you needed a library.

Since this feature was finally integrated into java itself with java 9 and you don't need an external library anymore, I would argue Map.of is preferrable.

However, in terms of readability, I have always hated that Map.of as well as List.of return immutable implementations, which is not what an inexperienced (=has not fallen into that trap yet) developer expects.

If you are using guava anyways, ImmutableMap.of is the more readable option, but that's up to you.

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