泛型类使用泛型参数

时间:2014-07-19 03:01:17

标签: java generics

情况

我正在创建一个如下所示的图表类:

class ImmutableGraph<G> {
    Node<G> selectedNode;
    private ImmutableGraph(Node<G> initialNode) { selectedNode = initialNode; }

    //many more things
}

我目前正在使用(嵌套)构建器类,如此

public static class GraphBuilder<B> {
    Node<B> currentNode;
    public GraphBuilder(B value){ currentNode = new Node(value); }
    public ImmutableGraph<B> build(){
        return new ImmutableGraph<B>(currentNode);
    }

    //many more things
}

使用(嵌套)节点类

private static class Node<N> {
    private final N value;
    Array<Nodes<N>> neighbours;
    public Node(N v){ value = v; }

    //many more things
}

问题

我找不到使用构建器实例化ImmutableGraph的方法,因为返回类型不正确。实际上,汇编表明GraphBuilder.build()应该返回类型ImmutableGraph<Node<B>>而不是ImmutableGraph<B>

现在我发现的唯一解决方案是将返回类型更改为ImmutableGraph<Node<B>>,但由于所有图形(除了空图形)都是节点图形,因此感觉很愚蠢。 Node类型也很混乱,因为用户永远不会与之交互。

编辑:

  • 更正了&#34; new&#34;在建造者的工厂方法

1 个答案:

答案 0 :(得分:0)

我认为您的构建方法应该return new ImmutableGraph<B>(currentNode);

import java.util.List;

public class ImmutableGraph<G> {
Node<G> selectedNode;

private ImmutableGraph(Node<G> initialNode) {
    selectedNode = initialNode;
}

// many more things

public static class GraphBuilder<B> {
    Node<B> currentNode;

    public GraphBuilder(B value) {
        currentNode = new Node<B>(value);
    }

    public ImmutableGraph<B> build() {
        return new ImmutableGraph<B>(currentNode);
    }

    // many more things
}

private static class Node<N> {
    private final N value;
    List<Node<N>> neighbours;

    public Node(N v) {
        value = v;
    }

    // many more things
}

public static void main(String[] args) {
    GraphBuilder<Integer> builder = new GraphBuilder<Integer>(Integer.MAX_VALUE);
    ImmutableGraph<Integer> graph = builder.build();
    System.out.println(graph.selectedNode.value);
}
}