سؤال

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?

هل كانت مفيدة؟

المحلول

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) {}

نصائح أخرى

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);
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top