osh
osh

Reputation: 1261

How to make a hashmap that contains SomeType<K,V>?

map = new HashMap<Class<? extends AbstractDAO<K,V>>, AbstractDAO<K,V>>);

is not allowed

Is there any way to achieve something like this?

Upvotes: 0

Views: 72

Answers (2)

Bohemian
Bohemian

Reputation: 425188

Sure you can, as long as you declare K and V as types.

Here I've declared them as method types:

public static class AbstractDAO<K, V> {
}

public static <K, V> void typedMethod() {
    Map<Class<? extends AbstractDAO<K, V>>, AbstractDAO<K, V>> map 
      = new HashMap<Class<? extends AbstractDAO<K, V>>, AbstractDAO<K, V>>();
}

Or if you don't want to declare the types, leave everything "unknown" with wildcards everywhere:

public static void method() {
    Map<Class<? extends AbstractDAO<?, ?>>, AbstractDAO<?, ?>> map = new HashMap<Class<? extends AbstractDAO<?, ?>>, AbstractDAO<?, ?>>();
}

All of the above code compiles.

Upvotes: 1

Sumit Singh
Sumit Singh

Reputation: 15896

Like following :

 class Test<K, V> {
    Map<K, V> map = new HashMap<Class<? extends AbstractDAO<K,V>>, AbstractDAO<K,V>>();
 }

Upvotes: 1

Related Questions