I’m writing a simple HashMap-based Cache that works as follows:
- If the requested
keyis in cache, return itsvalue. - If the requested
keyis not there, run a method that producesvaluebased onkey, store both, returnvalue.
The code:
import java.util.HashMap;
abstract class Cache<K, V> extends HashMap<K, V> {
@Override
public V get(Object key) {
if (containsKey(key)) {
return super.get(key);
} else {
V val = getData(key);
put((K)key, val); // this is the line I'm discussing below
return val;
}
}
public abstract V getData(Object key);
}
It’s pretty straightforward and works well. However, I hate the Sun’s decision for get() to take an Object as its argument and not K. I’ve read enough about it to know that it has some rationale behind it (with which I don’t agree, but that’s another story).
My problem is in the commented line, because it seems that the cast has to be unchecked. Due to type erasure, there’s no way I can check whether key is of type K (which is needed for proper put() functionality) and the method is, therefore, error prone.
One solution would be to switch from “is a” to “has a” HashMap relationship which is much nicer and clean, but then Cache can’t implement Map which would be nice for several reasons. The code:
import java.util.HashMap;
import java.util.Map;
abstract class Cache<K, V> {
private final Map<K, V> map = new HashMap<K, V>();
public V get(K key) {
if (map.containsKey(key)) {
return map.get(key);
} else {
V val = getData(key);
map.put(key, val);
return val;
}
}
public abstract V getData(K key);
}
Can anyone come up with any other (even hackish) solution, so that I could maintain Cache to be a Map and still be type safe in the terms of get(Object key) and put(K key, V val)?
The only thing I can think of is to make another method named i.e. getValue(Key k) that would delegate to get(Object key), but then I can’t force anyone to use the new method instead of the usual one.
Nope. You’ve found the right solution in switching to a “has-a” relationship. (Frankly, having the
getmethod compute a new value if one doesn’t already exist is surprising, violates theMapcontract, and can lead to extremely weird behavior for a number of other methods. This was a big part of why Guava moved away fromMapMaker, which offered almost this exact behavior — because it was just so riddled with issues.)That said, what e.g. Guava’s
Cachedoes is it exposes aMap<K, V> asMap()view, which is a thing you could do. That gives you most of the advantages of aMapwithout compromising on type safety.