1

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • By convention in Java class names start with uppercase (so PriorityQueue would be the choice) and method names start with lower case, so method Push should be push. – Igor Rodriguez Dec 15 '13 at 12:24
  • I don't use methods from Java.util and I didn't want to override them, I have defined my own priorityQueue, with my own methods. – user3042601 Dec 15 '13 at 12:30
  • You wouldn't override PriorityQueue by using the same name if you have a different package location. Also, prefer to use names that differ the ones in the standard libraries, such as MyPriorityQueue. Anybody reading the code including you in the future will appreciate this. – Igor Rodriguez Dec 15 '13 at 13:28

2 Answers2

2

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) {}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

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);
    }
}
Igor Rodriguez
  • 1,196
  • 11
  • 16
  • Did you try it? It won't compile. – Rohit Jain Dec 15 '13 at 12:27
  • Yes, I did try it and yes, it does compile. I have used it several times recently. What I noticed as well is that it's overkill for the OP's requirements and the answer of @Elliot Frisch is much simpler (and includes the "extends Comparable" that I forgot). – Igor Rodriguez Dec 15 '13 at 13:33
  • I don't see how your method as it stands compiles. The `push` method for `P` expects a `Comparable`, whereas you are just pushing elements from `Collection`, wherein `T` doesn't have any bounds. – Rohit Jain Dec 15 '13 at 13:36