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