简体   繁体   English

从Java中的另一个类“导入”泛型类型

[英]“Importing” generic type from another class in Java

I am trying to represent a Graph with Nodes and Edges. 我试图用节点和边表示图。

I have a class Node which has to be: 我有一个类Node必须是:

public class Node<NodeType>

and another class Edge, which I am allowed to parameterize in any way. 还有另一个Edge类,我可以用任何方式对其进行参数化。 At first I thought Edge<EdgeType> , but since they have Nodes as an atribute, I ended up doing the following (mostly because Eclipse told me about Node being a raw type if I did not parameterize it) 起初我以为Edge<EdgeType> ,但是由于它们将Nodes作为属性,所以我最终做了以下事情(主要是因为Eclipse告诉我,如果不对Node进行原始设置,则Node是原始类型)

public class Edge<EdgeType, NodeType> {
    private Node<NodeType> start;
    private Node<NodeType> end;
    private EdgeType value;
    ...
}

This gives me the ability to work without problems in the Edge class, but there are some methods in the Node class which require working with Edges, such as 这使我能够在Edge类中正常工作,但是Node类中有一些方法需要使用Edge,例如

public List<EdgeType> edgesValues(Node<NodeType> node) {
    /*Returns a list of values of the edges between the node it is called on and the node given by argument*/
}

which I can't use because EdgeType is not defined. 由于未定义EdgeType,因此无法使用。 Since I cannot add another parameter in the Node class, I do not know how to "import" EdgeType into it. 由于无法在Node类中添加另一个参数,因此我不知道如何将EdgeType“导入”到该类中。

I would put edgesValues method into a separate class that's parametrized by both NodeType and EdgeType : 我会将edgesValues方法放到一个由NodeTypeEdgeType参数化的单独的类中:

class Node<N> {
    N value;
}

class Edge<E, N> {
    Node<N> from;
    Node<N> to;
    E value;
}

class Graph<E, N> {     
    Node<N> newNode(N nodeVal) {
        ...
    }

    Edge<E, N> newEdge(E edgeVal, Node<N> from, Node<N> to) {
        ...
    }

    List<E> edgesValues(Node<N> node) {
        ...
    }
}

If you "have a class Node which has to be" something fixed, then you should remove the EdgeType from the Edge , you aren't using it anyway: 如果您“固定了必须具有的类Node”,则应该从Edge删除EdgeType ,无论如何都不要使用它:

 public class Edge<N> {
    private Node<N> start; 
    private Node<N> end;
    private int value;
 }

In your Node class, you don't need any additional type parameters now: 在您的Node类中,现在不需要任何其他类型参数:

 public List<Edge<N>> edges(...) { ... }

You probably won't need anything more complex than int 's anyway. 无论如何,您可能不需要比int更复杂的东西。

Your solution is quite simple, use generic methods : 您的解决方案非常简单,请使用通用方法:

public <EdgeType> List<EdgeType> edgesValues(Node<NodeType> node) {

}

but passing a Node<NodeType> as parameter within a instance of Node<NodeType> doesnt make much sense - methinks you got yourself a design flaw right there, maybe you should use another design pattern 但经过一个Node<NodeType>作为参数的实例中的Node<NodeType>犯规多大意义-记错你拥有属于自己的设计缺陷在那里,也许你应该用另一种设计模式

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

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