Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImmutableMap.of() workaround for HashMap in Maps?

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.

like image 951
Premraj Avatar asked May 10 '11 09:05

Premraj


People also ask

How do you make a HashMap key immutable?

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.

What is the best alternative for HashMap in Java?

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.

Is Guava ImmutableMap thread-safe?

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.


1 Answers

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(); 
like image 191
Jesper Avatar answered Sep 30 '22 19:09

Jesper