There are utility methods to create ImmutableMap
like Immutable.of(Key, value)
and its overload.
But such methods don't exist for HashMap
or LinkedHashMap
in Maps
class.
Is there any better way to do this or Guava assumes such a map is always a constant map and ImmutableMap
is best option to go with and don't need to provide a utility for HashMap
.
Both hashcode and equals method are used in put and get method of HashMap. You need to make sure you can always get the value object from the map after you put it with the key object. No matter you change the key object or not. But Immutable object is good enough to achieve that.
Whereas, ConcurrentHashMap is introduced as an alternative to the HashMap. The ConcurrentHashMap is a synchronized collection class. The HashMap is non-thread-safe and can not be used in a Concurrent multi-threaded environment.
Immutable map is born to thread-safe. You could use ImmutableMap of Guava. Show activity on this post. In short, no you don't need the map to be thread-safe if the reads are non-destructive and the map reference is safely published to the client.
Why would you want those for a regular HashMap
or LinkedHashMap
? You can just do this:
Map<String, Object> map = Maps.newHashMap(); map.put(key, value);
The thing with ImmutableMap
is that it is a little bit more cumbersome to create; you first need to make a Builder
, then put the key-value pairs in the builder and then call build()
on it to create your ImmutableMap
. The ImmutableMap.of()
method makes it shorter to write if you want to create an ImmutableMap
with a single key-value pair.
Consider what you'd have to write if you wouldn't use the ImmutableMap.of()
method:
ImmutableMap<String, Object> map = ImmutableMap.builder() .put(key, value); .build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With