【问题标题】:Using a class as a type parameter which may or may not contain another type parameter使用一个类作为类型参数,它可能包含也可能不包含另一个类型参数
【发布时间】:2016-10-12 14:13:41
【问题描述】:

我正在使用泛型,但遇到了问题。 所以我有一个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 类作为我的 Priority Queue 类中的类型时,如下所示:

private MaxPriorityQueue<Node> maxPriorityQueue;

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

我认为我在实现这一点时在概念上是错误的。 正确的方法应该是什么?

有没有办法我可以更改优先队列类,以便它可以将任何实现可比较接口的类(比如A)(不管A 是否包含类型参数)作为类型参数.?

【问题讨论】:

  • 请张贴minimal reproducible example的问题。
  • @SleimanJneidi :对不起,我编辑了这个问题。
  • 此处的完整示例:ideone.com/6e0QZ4
  • 为什么使用Node 作为原始类型?添加类型参数可修复错误。

标签: java generics type-parameter


【解决方案1】:

如果我正确理解您的要求,您需要强制您的 PriorityQueue 接受为自己实现可比较接口的对象。在这种情况下,您只需要:

class PriorityQueue<Item extends Comparable<Item>> {

最终,如果您想要节点有效负载的类型参数:

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

这样你就可以这样做了:

private PriorityQueue<Node<Integer>> maxPriorityQueue;

喜欢这里:https://ideone.com/GBnHp7 (?)(也请查看 cmets)

【讨论】:

    【解决方案2】:

    你可以做你所做的。您只需要在声明队列时指定 Node&lt;T&gt; 的类型,如下所示:

    private PriorityQueue<Node<String>> queue;
    

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-06
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多