使用类作为可能包含也可能不包含其他类型参数的类型参数
问题描述:
我正在使用泛型,我遇到了一个问题。 所以我有一个Node class
其中有一个type parameter<T>
可扩展可比较。使用类作为可能包含也可能不包含其他类型参数的类型参数
public class Node<T extends Comparable<T>> implements Comparable<Node<T>> {
private T info;
private Node next;
private Node previous;
}
现在,我已经设计了另一类说Priority Queue class
其中也包含了相当的类型参数。
public class PriorityQueue<Item extends Comparable<Item>>
implements Iterable<Item> {
....
}
但是当我尝试在我的优先级队列类使用Node类的类型是这样的:
private MaxPriorityQueue<Node> maxPriorityQueue;
它给了我一个错误说,Type parameter Node is not defined within bounds, should implement java.lang.comparable
。
我想我在概念上是错误的在执行这个。 什么应该是正确的方法?
有没有一种方法可以改变Priority Queue类,以便它可以采用任何实现可比接口(不管A
是否包含类型参数)作为类型参数的类(比如A
)。
答
如果我正确理解您的要求,您需要强制您的PriorityQueue接受为自己实现可比接口的对象。在这种情况下,你只需要:
class PriorityQueue<Item extends Comparable<Item>> {
,最终,如果你想为你的节点的有效载荷类型参数:
class Node<T> implements Comparable<Node<T>> {
,这样就可以做到这一点:
private PriorityQueue<Node<Integer>> maxPriorityQueue;
喜欢这里:https://ideone.com/GBnHp7(?)(看看评论以及)
答
你可以做到完全你有什么即你只需要指定类型Node<T>
当你宣布你的队列中,这样的事情:
private PriorityQueue<Node<String>> queue;
祝你好运!
什么是DLLNode? –
请发表问题的[mcve]。 – Tunaki
@SleimanJneidi:对不起,我编辑了这个问题。 – poorvankBhatia