本文介绍了is List< List< String>> Collection< Collection< T>>的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个方便的泛型函数,用于将集合集合转换为单个集合:

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

然后我试图调用它:

  List< List< String>> resultLists = ...; 
Set< String> labelsSet = CollectionsHelper.makeSet(resultLists);

,我收到以下错误:



<$ CollectionsHelper
中的p $ p> < T> makeSet(java.util.Collection< java.util.Collection< T>>)不能应用于(java.util.List< java.util.List< java.lang.String>>)

c> List 集合 String T 。那么为什么这不工作,如何解决呢?

解决方案
  < T>设置< T> makeSet(Collection< ;? extends Collection< T>> a_collection){
Iterator< ;? extends Collection< T>> it = a_collection.iterator();
设置< T> result = new HashSet< T>();
while(it.hasNext()){
result.addAll(it.next());
}
return result;
}


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?

解决方案
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;
}

这篇关于is List&lt; List&lt; String&gt;&gt; Collection&lt; Collection&lt; T&gt;&gt;的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 15:50