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