【问题标题】:Not able to pass collections classes as a parameter in a method with generic无法在具有泛型的方法中将集合类作为参数传递
【发布时间】:2018-03-13 05:45:17
【问题描述】:

我的程序的动机是用于将随机字符串添加到集合类中,如 ArrayList、LinkedList 和 HashSet。我创建了一个带有泛型参数的类,并希望将这些类引用传递给一个接受集合类型参数的方法。

当我创建 ArrayList 和 HashSet 类型的对象时,没有编译错误。但是当我使用 LnkedList 创建时,出现编译错误。

public class CollectionPerformace<T extends Collection<String>> {

public void calculatePerformance(T elements) {
    for (int i = 1; i <= 100000; i++) {
        elements.add(UUID.randomUUID().toString());
    }
}

public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();
    LinkedList<String> linkedList = new LinkedList<String>();
    HashSet<String> hashSet = new HashSet<String>();
    TreeSet<String> treeSet = new TreeSet<String>();
    CollectionPerformace<ArrayList<String>> arrayListPerformance = new 
     CollectionPerformace<>();
    arrayListPerformance.calculatePerformance(arrayList);
    **CollectionPerformace<LinkedList<String>> linkedListPerformance = new 
    CollectionPerformace<>();**
    linkedListPerformance.calculatePerformance(linkedList);
    CollectionPerformace<HashSet<String>> hashSetPerformance = new 
     CollectionPerformace<>();
    hashSetPerformance.calculatePerformance(hashSet);
    CollectionPerformace<TreeSet<String>> treeSetPerformance = new 
    CollectionPerformace<>();
    treeSetPerformance.calculatePerformance(treeSet);
  }
}

错误: 在标有粗体的行中出现错误。 此行有多个标记 - 绑定不匹配:LinkedList 类型不是 CollectionPerformace 类型的有界参数 > 的有效替代品 - 无法推断 CollectionPerformace

的类型参数

我需要任何人的帮助。

【问题讨论】:

  • 这段代码没有任何错误。我正在使用 JDK 8。

标签: java collections linked-list


【解决方案1】:

JVM 使用过吗? 对于 Java 8,这是一个有效的代码,并且运行良好。

HTH, 加尔

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 2018-09-27
    相关资源
    最近更新 更多