gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:36:26 25 4
gpt4 key购买 nike

我在使用泛型时遇到了一个问题。所以我有一个 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> {

....

}

但是当我像这样在我的优先级队列类中尝试使用节点类作为类型时:

private MaxPriorityQueue<Node> maxPriorityQueue;

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

我认为我在实现这个概念上是错误的。正确的做法应该是什么?

有没有一种方法可以更改优先级队列类,以便它可以将实现可比较接口(interface)的任何类(比如 A)作为类型参数(无论 A 是否包含类型参数) .?

最佳答案

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

class PriorityQueue<Item extends Comparable<Item>> {

最后,如果你想要一个类型参数作为你节点的负载:

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

这样你就可以这样做:

private PriorityQueue<Node<Integer>> maxPriorityQueue;

喜欢这里:https://ideone.com/GBnHp7 (?)(也看看评论)

关于java - 使用一个类作为类型参数,它可能包含也可能不包含另一个类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37768081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com