Is List<List<String>> an instance of Collection<Collection<T>>?

collections, covariance, generics, java

Solution

public static <T> Set<T> makeSet(Collection<? extends Collection<T>> a_collection) {
    Iterator<? extends Collection<T>> it = a_collection.iterator();
    Set<T> result = new HashSet<T>();
    while (it.hasNext()) {
            result.addAll(it.next());
    }
    return result;
}

Problem

I wrote this handy, generic function for converting a collection of collections into a single set: ``` public static <T> Set<T> makeSet(Collection<Collection<T>> a_collection) { Iterator<Collection<T>> it = a_collection.iterator(); Set<T> result = new HashSet<T>(); while (it.hasNext()) { result.addAll(it.next()); } return result; } ``` Then I tried to call it: ``` List<List<String>> resultLists = ... ; Set<String> labelsSet = CollectionsHelper.makeSet(resultLists); ``` and I received the following error: ``` <T>makeSet(java.util.Collection<java.util.Collection<T>>) in CollectionsHelper cannot be applied to (java.util.List<java.util.List<java.lang.String>>) ``` Now a `List` is a `Collection`, and a `String` is a `T`. So why doesn't this work and how do I fix it?

Original source