Search code examples
javawildcardgeneric-method

Wildcard parameter in method


I have defined the following class:

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

It contains the following methods:

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

I need to write a method that copies elements from a collection to a priorityQueue

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

}

I get the error:

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)

Why I can't write the method:

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

I get the error:

Syntax error on token "extends",, expected

How can I declare the method to copy the elements?


Solution

  • Because T is already defined at that point, try this instead

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