0

I searched through a lot of questions and other internet articles, but I can't seem to find the one that caters to my specific case, and none of the other ones solutions worked for me.

I have this interface here:

public interface PriorityQueueInterface<T extends Comparable<? super T>>

I need to make a priority queue class to implement this interface, so I typed it out like this:

public class ArrayPriorityQueue<T> implements PriorityQueueInterface<Comparable<? super T>>

However, it is not compiling as I get this error:

type argument Comparable is not within bounds of type-variable T#2 where T#1,T#2 are type-variables: T#1 extends Object declared in class ArrayPriorityQueue T#2 extends Comparable declared in interface PriorityQueueInterface

I tried all types of combinations, but nothing seems to work. How do I write the class declaration so that it compiles?

Vipin CP
  • 3,642
  • 3
  • 33
  • 55
gameCoder95
  • 349
  • 1
  • 5
  • 19

1 Answers1

1

Seems like what you want is to declare the type variable with the same bound, then pass that on as an argument to the interface:

public class ArrayPriorityQueue<T extends Comparable<? super T>>
    implements PriorityQueueInterface<T> {...}
Radiodef
  • 37,180
  • 14
  • 90
  • 125
  • Well that was easy, thank you so much! I'm quite new to generics, so if you can, can you please explain to me what the statement "T extends Comparable super T>>" means? I have a bit of an idea after searching around but I still have trouble understanding that specific line. – gameCoder95 Aug 04 '16 at 13:41
  • `T extends Comparable` means that `T` has to implement the `Comparable` interface. `T` gets passed to `Comparable` as an argument in `Comparable` because a class implementing `Comparable` should always provide itself as an argument, for example `class String implements Comparable`. The `? super T` part just makes the bound a little more permissible in that it lets us have a situation like `class A implements Comparable` and `class B extends A`. `B` is a `Comparable` so the simpler type bound would reject it as an argument. – Radiodef Aug 04 '16 at 17:33
  • Awesome explanation, thanks! It helped me understand it much better. I just have one more small question: in the above ArrayPriorityQueue class, how would you instantiate an array of "T" objects? Apparently (T[])new Object[size] throws a runtime exception because apparently it can't cast a Comparable to it. – gameCoder95 Aug 05 '16 at 02:50
  • `(T[]) new Comparable>[size]`. (`T` is erased to its type bound `Comparable` so you use that instead of `Object`.) If you are doing generic arrays in that way, note that you can never expose the array to outside the class or else it will throw an exception. It needs to be `private` and you can't return it via a method. – Radiodef Aug 05 '16 at 03:10