Wildcard parameter in method

454 views Asked by At

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?

2

There are 2 answers

0
Elliott Frisch On BEST ANSWER

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) {}
3
Igor Rodriguez On

You are trying to use a wildcard of an undefined type in the static method. Being static, the wildcard definitions of the class are not valid, and you need to specify them in the method.

Add another wildcard, so the method ends like this:

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