情况
我正在制作一个如下所示的图形类:
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/