实现通用顶点和边类

时间:2015-12-11 22:33:27

标签: java generics

我想实现通用图表类。这些是我提出的:

public abstract class VertexBase<V extends VertexBase<V, E>, E extends EdgeBase<V, E>> {
    public final HashMap<V, E> inEdges = new HashMap<>();
    public final HashMap<V, E> outEdges = new HashMap<>();
}

public abstract class EdgeBase<V extends VertexBase<V, E>, E extends EdgeBase<V, E>> {
    public final V fromVertex;
    public final V toVertex;

    public EdgeBase(V from, V to) {
        fromVertex = from;
        toVertex = to;
        from.outEdges.put(to, get());
        to.inEdges.put(from, get());
    }

    protected abstract E get();
}

现在的问题是我必须实现Edge :: get everywhere:

@Override
protected Edge get() {
    return this;
}

编译器抱怨我在构造函数中调用了overridable方法。

有没有办法更好地实施这些?

1 个答案:

答案 0 :(得分:0)

当您实现扩展EdgeBase的新类时,您需要将所有E类型替换为Edge,而Edge必须扩展EdgeBase&lt; V,Edge&gt ;,例如:

public class EdgeBaseImpl<V extends VertexBase<V, Edge>> extends EdgeBase<V, Edge> {
  ...
  @Override
  protected Edge get() {
     return this;
  }
}