I'm writing a simple HashMap
-based Cache that works as follows:
key
is in cache, return its value
.key
is not there, run a method that produces value
based on key
, store both, return value
.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 get
method compute a new value if one doesn't already exist is surprising, violates the Map
contract, and can lead to extremely weird behavior for a number of other methods. This was a big part of why Guava moved away from MapMaker
, which offered almost this exact behavior -- because it was just so riddled with issues.)
That said, what e.g. Guava's Cache
does is it exposes a Map<K, V> asMap()
view, which is a thing you could do. That gives you most of the advantages of a Map
without compromising on type safety.
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