Nested generic java collections

I would call a method defined as

<T> void foo(Class<? extends Collection<T>>)

but the compiler does not allow me to pass

foo(ArrayList<Integer>.class);

What is the syntax for getting a class type of a generic type?

I implement the general case when I have

Map<Key, Collection<Value>>

and want to insert the value into the collection. If the collection does not exist, it must create a new one and paste the value into it. So far, I have the following code, but with security type warnings:

public static <K, V, C extends Collection<V>> boolean addToMappedCollectionNotNull(Map<K, C> aMap, K key, V element, Class<? extends Collection> type) {
    C collection = aMap.get(key);
    if (collection == null) {
        try {
            collection = (C)type.newInstance();
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        }
        aMap.put(key, collection);
    }

    return collection.add(element);
}
+3
source share
3 answers

As Boris said, you're probably looking for a MultiMap. But if you think you need to pass type information, this is a supertext type solution . Guice has a TypeLiteral implementation that you can look at.

+1
source

, Google Guava. Multimap<K, V>, V K.

, , . put(K, V), , , .

Multimap ListMultimap, SetMultimap SortedSetMultimap, V.

0

Foo (ArrayList.class);

class , .

You will have to reverse engineer this so that you do not introduce so much logic in one place. Perhaps separate the part that is testing for null Collection, and the part create it elsewhere, such as Factory.

0
source

All Articles