Java - Extending HashMap - Object vs. generics behaviour

25,440

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.

Share:
25,440
Petr Janeček
Author by

Petr Janeček

Stack Exchange - Favorite Users - A browser addon that highlights answers and questions by your favorite users!

Updated on April 30, 2020

Comments

  • Petr Janeček
    Petr Janeček about 4 years

    I'm writing a simple HashMap-based Cache that works as follows:

    1. If the requested key is in cache, return its value.
    2. If the requested 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.

  • Petr Janeček
    Petr Janeček about 12 years
    That'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 class final abstract (even though I knew 100% that it won't work) or just final (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
    Petr Janeček about 12 years
    It seems the MapMaker indeed did what I do :). I am partially aware of the weird behaviour. The method V getData(K key) is abstract and therefore is intended to be only specified (implemented) on Cache instantiation. I even tried to make the class final abstract (even though I knew 100% that it won't work) or just final (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 with asMap() giving a view it is.
  • Petr Janeček
    Petr Janeček about 12 years
    By 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
    Louis Wasserman about 12 years
    You...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
    Keenan Gebze over 10 years
    Is it really okay to switch to "HAS-A" relationship (for other Java program generally) ?
  • Petr Janeček
    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
    flow2k over 6 years
    Perhaps this is another example for Composition over inheritance?