Create a hashmap of immutable generic objects

caching, generics, java

Solution

Your thinking is good, and you're right that there's no built-in way of handling immutability.

However, you could try this:

interface Copyable<T> {
    T getCopy();
}

Then override the `get()` method to return copies instead of the value itself;

class CopyMap<K, V extends Copyable<V>> extends HashMap<K, V> {
    @Override
    public V get(Object key) {
        return super.get(key).getCopy();
    }
}

Then it's up to the implementation to return a copy of itself, rather than `this` (unless the class itself is immutable). Although you can't enforce that in code, you would be within your rights to publicly humiliate the programmer that doesn't conform.

Problem

I don't think that there is a way that is efficient (if at all) of doing this, but I figured I'd ask in case someone else knows otherwise. I'm looking to create my own Cache/lookup table. To make it as useful as possible, I'd like it to be able to store generic objects. The problem with this approach is that even though you can make a `Collections.unmodifiableMap, immutableMap, etc`, these implementations only prevent you from changing the Map itself. They don't prevent you from getting the value from the map and modifying its underlying values. Essentially what I'd need is for something to the effect of `HashMap<K, ? extends Immutable>`, but to my knowledge nothing like this exists. I had originally thought that I could just return a copy of the values in the cache in the get method, but since Java's `Cloneable` interface is jacked up, you cannot simple call ``` public V getItem(K key){ return (V) map.get(k).clone(); } ```

Original source

Related problems