5 ms·
final in Java is only immutable references. If I have: private final Map<String, String> map = new HashMap<>(); I cannot say map = someOtherMap;, but I can s
by _asummers 11y ago
final in Java is only immutable references.
If I have:
private final Map<String, String> map = new HashMap<>();
I cannot say map = someOtherMap;, but I can still say map.put("key", "value");.
- mbreese 11y agoBut you can wrap that Map with Collections.unmodifiableMap() for an immutable version.
- saryant 11y agoNot quite. If the original collection is modified, the "immutable" view will reflect that change. Plus, you can't statically know if the collection you're passed is immutable or not. Trying to modify it will just blow up at runtime.
- _asummers 11y agoIndeed, but there is no way to reflect that in the return type, besides the JavaDoc of course. If you try and modify it later, you'll get a runtime exception, which is a pretty crappy thing. One of the things I dislike most about the Collections API is that Mutable interfaces are not extensions of Immutable interfaces with just the addition of modifiers. I should be forced to say that I'm returning a Mutable version of a data structure in my return type.
- dorgo 11y ago> is that Mutable interfaces are not extensions of Immutable interfaces with just the addition of modifiers. I should be forced to say that I'm returning a Mutable version of a data structure in my return type. It wouldnt work. If MutableList<E> extends ImmutableList<E> then every MutableList is also an ImmutableList. This way you can be forced to return a MutableList, but not an ImmutableList.
- _asummers 11y agoFair point, you're absolutely correct. Admittedly I haven't given this a TON of thought, because it seems like something that can't be added anymore. Maybe the interfaces should be siblings, but since Java doesn't have a disjoint type, you might run into problems if something says it implements both MutableList and ImmutableList. Not sure if Java's type system is strong enough to deal with this problem.
- kilink 11y agoI think the Map interface should have been composed of two interfaces, ReadableMap and WriteableMap. Then APIs could return ReadableMap, which would lack the mutator methods altogether.
- dorgo 11y agoThen a Map would be a ReadableMap, but a ReadableMap wouldn't be a Map. If a method expects a Map, you would't be able to put a ReadableMap (or a WriteableMap) into it. My solution so far is to avoid to return a map or to expect a map as argument.