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.?
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)