razz
razz

Reputation: 10110

Can't resolve 'Type argument is not within bounds of type-variable' error

I have a generic class ShortestPathVertex which implements Comparable:

public class ShortestPathVertex<E extends Number> implements VertexInterface, Comparable<ShortestPathVertex<E>>

And another generic Class MinPriorityQueue that requires a Comparable type parameter:

public class MinPriorityQueue<T extends Comparable<T>>

And I need to create a MinPriorityQueue instance with ShortestPathVertex as the type parameter:

public static <E extends Number, T extends ShortestPathVertex<E>> void Dijkstra(WeightedDirectedGraph<T, E> G, int s) {
        MinPriorityQueue<T> Q = new MinPriorityQueue<>(G.getVertices(), G.V()); // error
}

When I compile it throws error:

ShortestPath.java:60: error: type argument T#1 is not within bounds of type-variable T#2
        MinPriorityQueue<T> Q = new MinPriorityQueue<>(G.getVertices(), G.V());
                         ^
  where T#1,E,T#2 are type-variables:
    T#1 extends ShortestPathVertex<E> declared in method <E,T#1>Dijkstra(WeightedDirectedGraph<T#1,E>,int)
    E extends Number declared in method <E,T#1>Dijkstra(WeightedDirectedGraph<T#1,E>,int)
    T#2 extends Comparable<T#2> declared in class MinPriorityQueue
ShortestPath.java:60: error: cannot infer type arguments for MinPriorityQueue<>
        MinPriorityQueue<T> Q = new MinPriorityQueue<>(G.getVertices(), G.V());
                                ^
2 errors

Considering that ShortestPathVertex implements Comparable i don't understand what is it complaining about. Why is it saying that ShortestPathVertex is not withing bounds of Comparable and how do I fix it. I'm using Java 7.0.

Upvotes: 2

Views: 1512

Answers (1)

Donat
Donat

Reputation: 4813

Change this line

public class MinPriorityQueue<T extends Comparable<T>>

to this:

public class MinPriorityQueue<T extends Comparable<? super T>>

The issue here is that T extends ShortestPathVertex<E> in method Dijkstra, so T needs not implement Comparable directly. But this was necessary in your version of MinPriorityQueue. My change fixes this problem.

Explanation: In MinPriorityQueue<T> Q = ... T is a subtype of ShortestPathVertex<E> which implements Comparable<ShortestPathVertex<E>>. This means T is comparable to values of type ShortestPathVertex<E> (which is a super type of T). But in your version of MinPriorityQueue you define that T must be comparable to the same type T. If you also want to accept super type, you must define it by <? super T>.

You can try (just for demonstration): In method Dijkstra substitute every occurence of T by ShortestPathVertex<E>. This works also with the simpler definition of class MinPriorityQueue.

Another example for using super in this way: Look at the method Collections.binarySearch in the Java Class Library.

Upvotes: 1

Related Questions