5

I want to create a mapping from (a) class type to (b) long (the identifier of the object of the defined class type) to (c) the object itself.

I have the following:

 protected HashMap<Class<?>, HashMap<Long, ?>> obj = new HashMap<Class<?>, HashMap<Long, ?>>();

Is it possible to somehow denote that the first ? must be of the same type than the second ?? I would expect something like this, but this is ofcourse not possible:

protected <T> HashMap<Class<T>, HashMap<Long, T>> obj = new HashMap<Class<T>, HashMap<Long, T>>();
5
  • 1
    You'll need to add that type definition <T> to the enclosing class or method that is using the HashMap.
    – Nate W.
    Dec 6, 2011 at 23:16
  • I think I can't. I am collecting/caching a set of class types in my map. Not just one. It can be of any type. Or am I seeing it wrong?
    – Japer D.
    Dec 6, 2011 at 23:17
  • 1
    very interesting point, but i don't think you can build a constraint like that unfortunately.
    – aishwarya
    Dec 6, 2011 at 23:21
  • 1
    You're seeing it wrong. <T> can be of any type, but all occurrences of T must be the same type.
    – Nate W.
    Dec 6, 2011 at 23:21
  • 1
    You can achieve much of the same by using your original definition with the unbounded wildcards, and adding / retrieving items from the map using generic methods that enforce your constraint. These wouldn't be typesafe all the way down, but well-encapsulated unsafe code is probably acceptable.
    – millimoose
    Dec 6, 2011 at 23:28

4 Answers 4

5

As an alternative, you could use a small amount of not-type-safe code encapsulated in a way that enforces your constraint:

class Cache {
    private Map<Class<?>, Map<Long, ?>> items = new HashMap<Class<?>, Map<Long, ?>>();

    private <T> Map<Long, T> getItems(Class<T> type) {
        @SuppressWarnings("unchecked")
        Map<Long, T> result = (Map<Long, T>) items.get(type);
        if (result == null) {
            result = new HashMap<Long, T>();
            items.put(type, result);
        }
        return (Map<Long, T>) result;
    }

    public <T> void addItem(Class<T> type, Long id, T item) {
        getItems(type).put(id, item);
    }

    public <T> T getItem(Class<T> type, Long id) {
        return type.cast(getItems(type).get(id));
    }
}

The type.cast() in getItem() isn't necessary for the compiler to not complain, but it would help catch an object of the wrong type getting into the cache early.

3
  • good solution and this could do the trick for all practical purposes!
    – aishwarya
    Dec 7, 2011 at 0:18
  • Thanks. This makes lots of sense. For the outside world, everything is safely typed. For the implementation, a 'safe cast' is used.
    – Japer D.
    Dec 7, 2011 at 12:19
  • By the way, you mention .cast() being done before putting it in the cache. In your code snippet, you are casting after retrieving it from the cache.
    – Japer D.
    Dec 7, 2011 at 12:29
2

Each occurence of a wildcard corresponds to a different type, and the only appropriate scope for a type parameter representing the type is the entry in the outer HashMap. Unfortunately, HashMap does not allow constraining the entry type in its type parameter like:

class Entry<K,V> {
    // fields omitted
}

class Map<E extends Entry<?,?> {

}

class EntityCacheEntry<E> extends Entry<Class<E>, Map<Entry<Long, E>>> { }

class EntityCache extends Map<EntityCacheEntry<?>> { }

Even if it did, there is no way to implement Map.get without using unchecked casts, because we'd have to constrain its type parameter to a particular member of the type family represented by E - and you can't constrain a type parameter of a type parameter in Java.

Therefore, your only recourse is writing a facade whose api enforces the type invariant, but internally uses casts:

class EntityCache {
    Map<Class<?>, Map<Long, Object>> map = new HashMap<>();

    public <E> void put(Class<E> clazz, long id, E entity) {
        map.get(clazz).put(id, entity);
        // TODO create map if it doesn't exist yet
    }

    public <E> E get(Class<E> clazz, long id) {
        return clazz.cast(map.get(clazz).get(id));
        // TODO what if not found?
    }
}
1
  • +1. Thanks for your answer. This is more or less the same approach as Inerdial's.
    – Japer D.
    Dec 7, 2011 at 12:26
0

You could extend the HashMap class with your specific generic definitions and make a generic class that takes the <T> as argument, something like this:

public class MyHashMap<T> extends HashMap<Class<T>, HashMap<Long, T>> { ...
7
  • 2
    This isn't what the OP was asking for. (What the OP was asking for is impossible anyway.)
    – millimoose
    Dec 6, 2011 at 23:25
  • 1
    Why? If he does this and then instantiates his object with the new type, it will enforce that both generic types in the HashMap definition are the same, which is what the OP wants.
    – olex
    Dec 6, 2011 at 23:36
  • 1
    If I understand the question right, he wants the map to have contents like this: {Foo.class => Map<Long, Foo>, Bar.class => Map<Long, Bar>}
    – millimoose
    Dec 6, 2011 at 23:52
  • Yes, and you could achieve just that: MyHashMap<Foo> obj = new MyHashMap<Foo>() would be an extended HashMap<Class<Foo>, HashMap<Long, Foo>>.
    – olex
    Dec 6, 2011 at 23:59
  • 1
    But, according to the OP's comment on the question, he wants the map keys to be Class objects for different types. A HashMap<Class<Foo>, ?> would be completely useless because there's only one instance of the type Class<Foo> in a JVM anyway. (Barring classloader use that's not relevant in most applications.)
    – millimoose
    Dec 7, 2011 at 0:13
0

What you probably want is: HashMap<Class<?>, HashMap<Long, Object>>. Because you will be putting objects of different types in it, Object is the type parameter that will allow you to add any type of object.

Don't get confused with the wildcard (?). It has the opposite meaning -- it means that the parameter is some type (thus all the objects must be of that type) but we don't know what it is, thus we can't put anything in it at all. That is not what you want.

2
  • I am really having difficulties to understand why <?> is not equal to <Object>. Doesn't '?' mean 'anything', which is an Object? Do you want me to make a new topic for this?
    – Japer D.
    Dec 7, 2011 at 12:21
  • 1
    You should probably read up on this. Basically let's say you have a reference of type List<?>; it could point to an object of type List<String> or List<Integer> or List<SomeRandomType>. If it were an object of type List<String>, you can't add Integers to it. In other words, <?> means that there is some type parameter (thus all elements are required to be of that type) but we don't know what that type parameter is; so we can't safely add anything to it. On the other hand, with a List<Object> you can add anything to it.
    – newacct
    Dec 8, 2011 at 23:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.