java - 泛型类使用泛型参数

标签 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类型也令人困惑,因为用户从不与其交互。

编辑:

  • 更正了构建器工厂方法中的"new"

最佳答案

我认为你的构建方法应该 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);
}
}

关于java - 泛型类使用泛型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24836315/

相关文章:

java - Guice 辅助注入(inject)几个工厂方法和空参数

java - 如何在 XML 中添加 CDATA 而不会丢失 java 中的 <br/> 标记?

java - 无法 Autowiring 数据源

java - 实现抽象泛型方法

java - 使用泛型来增加集合

java - 如何解析未定义长度的剩余对象响应

java - 如何在多个 box2d 对象层中绘制相同的 Sprite ?

generics - kotlin 中的递归类型参数

typescript :如何指定箭头函数类型的通用参数

swift - '[任务] ?' is not convertible to ' 可选<[任何]>'