使用 class 作为类型参数,它可能包含也可能不包含另一个类型参数

Using a class as a type parameter which may or may not contain another type parameter

我在使用 Generics 时遇到了问题。 所以我有一个 Node class,它有一个 type parameter<T>,它扩展了 comparable.

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

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

}

现在,我设计了另一个 class 说一个 Priority Queue class,它也包含一个可比较的类型参数。

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

....

}

但是当我尝试使用节点 class 作为我的优先队列 class 中的类型时,如下所示:

private MaxPriorityQueue<Node> maxPriorityQueue;

它给我一个错误提示,Type parameter Node is not defined within bounds, should implement java.lang.comparable

我认为我在执行此操作时在概念上是错误的。 正确的方法应该是什么?

有没有一种方法可以更改优先级队列 class,以便它可以采用任何实现可比接口的 class(例如 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;

祝你好运!