Java - Extending HashMap - Object vs. generics behaviour
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.
Petr Janeček
Stack Exchange - Favorite Users - A browser addon that highlights answers and questions by your favorite users!
Updated on April 30, 2020Comments
-
Petr Janeček about 4 years
I'm writing a simple
HashMap
-based Cache that works as follows:- If the requested
key
is in cache, return itsvalue
. - If the requested
key
is not there, run a method that producesvalue
based 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 anObject
as its argument and notK
. 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 typeK
(which is needed for properput()
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 thenCache
can't implementMap
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 aMap
and still be type safe in the terms ofget(Object key)
andput(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 toget(Object key)
, but then I can't force anyone to use the new method instead of the usual one. - If the requested
-
Petr Janeček about 12 yearsThat's the fun part about it - there's no logic! The method is
abstract
and therefore should be only specified (implemented, overriden - whichever you like most) on Cache instantiation. I even tried to make the classfinal abstract
(even though I knew 100% that it won't work) or justfinal
(with the method overridable by anonymous inner class - doesn't, of course, work either) to ensure nobody will try to subclass this dangerous piece of code with some business logic. -
Petr Janeček about 12 yearsIt seems the
MapMaker
indeed did what I do :). I am partially aware of the weird behaviour. The methodV getData(K key)
isabstract
and therefore is intended to be only specified (implemented) on Cache instantiation. I even tried to make the classfinal abstract
(even though I knew 100% that it won't work) or justfinal
(with the method overridable by anonymous inner class - doesn't, of course, work either) to ensure nobody will try to subclass this dangerous piece of code with some business logic. Anyway, thanks a lot, the "has-a" relationship withasMap()
giving a view it is. -
Petr Janeček about 12 yearsBy the way, I can't believe I missed the Guava's Cache. I won't use it now (when I have my own implementation) out of pride, but if I knew that yesterday... :)
-
Louis Wasserman about 12 yearsYou...should consider using Guava's
Cache
anyway. It's used in Google production, so it's been heavily tested and optimized, and it's got lots of handy features. -
Keenan Gebze over 10 yearsIs it really okay to switch to "HAS-A" relationship (for other Java program generally) ?
-
Petr Janeček over 10 years@KeenanGebze Has-a (composition) is mostly preferred, yes. Is-a (inheritance) is usually used wrongly, anyway (as was this case here), so it should be only used when really needed and when you're sure it's architecturally justified.
-
flow2k over 6 yearsPerhaps this is another example for Composition over inheritance?