Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - unmodifiable key set map

I am looking for a way to provide a Map with pre-defined (as in runtime immutable, not compile time const) constant key set, but modifiable values.

The JDK provides Collections.unmodifiableMap factory method, which wraps a Map and provides an immutable view of it.

Is there a similar way to wrap a Map so that only it's keys are immutable? For instance, put(K,V) will replace the value of existing keys, but throw UnsupportedOperationException if the key does not exist.

like image 638
Elist Avatar asked May 16 '17 09:05

Elist


People also ask

How do you make a Map Unmodifiable?

An Unmodifiable Map is just a wrapper over a modifiable map and it doesn't allow modifications to it directly: Map<String, String> mutableMap = new HashMap<>(); mutableMap. put("USA", "North America"); Map<String, String> unmodifiableMap = Collections.

What is Unmodifiable Map?

Unmodifiable maps are “read-only” wrappers over other collections. They do not support any modification operations such as add, remove, and clear, but their underlying collection can be changed. Maps that additionally guarantee that no change in the Collection object will ever be visible are referred to as immutable.

What is an unmodifiable set in Java?

unmodifiableSet( new HashSet<String>() ); creates an instance of a Set which will throw UnsupportedOperationException if one attempts to call fixed. add() or fixed.

Is Unmodifiable Map thread safe?

unmodifiableMap(deliverersMod); as well as the preceding operations where the map is populated. So your code is thread safe and your getDeliverers method will return a result based on the latest version of your map.


1 Answers

Use an enum as the key. Then one needn't care if they can add a new key since the key domain is fixed and finite. In fact, that's such a standard use case that Java provides java.util.EnumMap<K extends Enum<K>,V> http://docs.oracle.com/javase/8/docs/api/java/util/EnumMap.html

like image 168
Lew Bloch Avatar answered Oct 16 '22 11:10

Lew Bloch