2
votes

I am working with Generics and i encountered a problem. So i have a Node class which has a type parameter<T> which extends comparable.

public class Node<T extends Comparable<T>> implements Comparable<Node<T>> {

    private T info;
    private Node next;
    private Node previous;

}

Now, i have designed another class say a Priority Queue class which also contains a comparable type parameter.

public class PriorityQueue<Item extends Comparable<Item>> 
implements Iterable<Item> {

....

}

But when i try and use a Node class as a Type in my Priority Queue class like this:

private MaxPriorityQueue<Node> maxPriorityQueue;

It gives me an error saying , Type parameter Node is not defined within bounds, should implement java.lang.comparable.

I think i am conceptually wrong at implementing this. What should be the correct way?

Is there a way i can change Priority Queue class, so that it can take any class(say A) which implements comparable interface (irrespective of the fact whether A contains type parameter or not) as a type parameter.?

2
Please post a minimal reproducible example of the issue.Tunaki
@SleimanJneidi : Sorry i edited the question.poorvank
full example here: ideone.com/6e0QZ4guido
Why are you using Node as a raw type? Adding a type argument fixes the error.Jorn Vernee

2 Answers

1
votes

If I understand correctly your requirements, you need to enforce your PriorityQueue to accept objects that implement the comparable interface for themselves. In that case, you just need:

class PriorityQueue<Item extends Comparable<Item>> {

and eventually if you want a type parameter for the payload of your Node:

class Node<T> implements Comparable<Node<T>> {

so that you can do this:

private PriorityQueue<Node<Integer>> maxPriorityQueue;

Like here: https://ideone.com/GBnHp7 (?) (look at the comments as well)

1
votes

You can do exactly what you have done. You just need to specify the type for Node<T> when you declare your queue, something like this:

private PriorityQueue<Node<String>> queue;

Good luck!