方法中的通配符参数

时间:2013-12-15 12:09:28

标签: java wildcard generic-method

我定义了以下类:

 public class priorityQueue<T extends Comparable<T>> implements Iterable<T> 

它包含以下方法:

  • public boolean Push(T Node)
  • public T Pop()
  • public Iterator iterator()

我需要编写一个方法,将集合中的元素复制到priorityQueue

public static<T>  void copy(Collection<T> source, priorityQueue<? extends Comparable<T>> dest) { 
    for(T elem:source){
        dest.Push(elem);
    }

}

我收到错误:

The method Push(capture#1-of ? extends Comparable<T>) in the type priorityQueue<capture#1-of ? extends Comparable<T>> is not applicable for the arguments (T)

为什么我不能写方法:

public static<T>  void copy(Collection<T> source, priorityQueue<T extends Comparable<T>> dest) 

我收到错误:

Syntax error on token "extends",, expected

如何声明复制元素的方法?

2 个答案:

答案 0 :(得分:2)

由于此时已定义T,请尝试使用

public static<T extends Comparable<T>> 
 void copy(Collection<T> source, priorityQueue<T> dest) {}

答案 1 :(得分:0)

您正尝试在静态方法中使用未定义类型的通配符。作为静态,类的通配符定义无效,您需要在方法中指定它们。

添加另一个通配符,因此方法结束如下:

public static<T, P extends PriorityQueue<Comparable<T>>>  void copy(Collection<T> source, P dest) { 
    for(T elem:source){
        dest.Push(elem);
    }
}
相关问题