简体   繁体   English

Java抽象类泛型方法参数

[英]Java abstract class generic method parameter

I'm running into a problem with java abstract classes and generic functions. 我遇到了java抽象类和泛型函数的问题。 The implementation is a node class in a graph for Dijkstra's algorithm. 该实现是Dijkstra算法的图中的节点类。

public abstract class Node {

    float distance;
    Node parent;

    public void relax(Node parent, Edge edge, PriorityQueue<? extends Node> priorityQueue) {
        if (this.distance > parent.distance + edge.weight){
            this.distance = parent.distance + edge.weight;
            this.parent = parent;
            priorityQueue.remove(this);
            priorityQueue.add(this);
        }
    }
}

The problem is the line: 问题是这条线:

priorityQueue.add(this); priorityQueue.add(本);

Because this references the Node class (which is abstract) it cannot be added to the priority queue and should in fact be of type ? 因为引用了Node类(它是抽象的),所以它不能被添加到优先级队列中并且实际上应该是类型的 (the subclass of node) denoted in ? (节点的子类)表示在 extends Node . 扩展节点 How to I reference this subclass type? 如何引用此子类类型?

Thanks in advance. 提前致谢。

I'm not sure what you want to achieve. 我不确定你想要达到什么目的。 I see two variants. 我看到两个变种。 Either you will use one type of subclass of a node and then you can write something like: 您将使用一种类型的节点子类,然后您可以编写如下内容:

public <T extends Node> void relax(T parent, Edge edge, PriorityQueue<T> priorityQueue) {
    if (this.distance > parent.distance + edge.weight){
        this.distance = parent.distance + edge.weight;
        this.parent = parent;
        priorityQueue.remove(this);
        priorityQueue.add((T) this);
    }
}

Or you want to just use different types of nodes and mix and match them but then the type for queue will be just PriorityQueue<Node> . 或者你想只使用不同类型的节点并混合和匹配它们,但队列的类型将只是PriorityQueue<Node>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM