方法中的通配符参数



我定义了以下类:

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

它包含以下方法:

  • 公共布尔推送(T节点)
  • 公共T Pop()
  • 公共迭代器迭代器()

我需要编写一个方法,将集合中的元素复制到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

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

因为此时已经定义了T,请尝试使用

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

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

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

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

最新更新