gpt4 book ai didi

java - 用 Java 编写一个树类,其中每个级别都有唯一的对象类型

转载 作者:行者123 更新时间:2023-11-29 08:16:19 27 4
gpt4 key购买 nike

我需要用 Java 编写一个树类,其中每个级别都有唯一的对象类型。下面的写法没有利用泛型,导致大量重复代码。有没有办法用泛型来写这个?

 public class NodeB {
private String nodeValue;
//private List<NodeB> childNodes;
// constructors
// getters/setters
}

public class NodeA {
private String value;
private List<NodeB> childNodes;
// constructors
// getters/setters
}

public class Tree {
private String value;
private List<NodeA> childNodes;
// constructors
// tree methods
}

最佳答案

这是一个简单的实现,但足以给出总体思路:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class GenericNode {

public static abstract class AbstractNode<V, N> {
private V value;
private List<N> children;

public AbstractNode(V value, N... children) {
this.value = value;
this.children = children != null ? Arrays.asList(children)
: Collections.<N> emptyList();
}

public V getValue() {
return value;
}

public List<N> getChildren() {
return children;
}

public int getNumberOfChildren() {
return children.size();
}

@Override
public String toString() {
return value.toString() + "->" + children.toString();
}
}

// leaf node type, ignore type of children
public static class NodeB extends AbstractNode<String, Object> {

public NodeB(String value, Object... nodes) {
super(value, nodes);
}
}

// example of typical node in the mid of tree
public static class NodeA extends AbstractNode<String, NodeB> {
public NodeA(String value, NodeB... nodes) {
super(value, nodes);
}
}

// top level node type
public static class Tree extends AbstractNode<String, NodeA> {
public Tree(String value, NodeA... nodes) {
super(value, nodes);
}
}

@SuppressWarnings({ "rawtypes", "unchecked" })
public static <V, N extends AbstractNode> int getNodeCount(
AbstractNode<V, N> node) {
int nodeCount = node.getChildren().size();
for (N child : node.getChildren()) {
nodeCount += getNodeCount(child);
}
return nodeCount;
}

public static void main(String[] args) {
NodeB nodeB1 = new NodeB("Leaf node 1");
NodeB nodeB2 = new NodeB("Leaf node 2");
NodeA nodeA = new NodeA("Node with children", nodeB1, nodeB2);
NodeA emptyNodeA = new NodeA("Empty node");
Tree tree = new Tree("Tree", nodeA, emptyNodeA);
System.out.println(tree);
System.out.println(1 + getNodeCount(tree));
}
}

您可以让 N 和 V 类型实现特定的接口(interface),这样就可以对值和/或子项调用一些常见的操作。

编辑:使用递归方法更新实现节点计数检索

关于java - 用 Java 编写一个树类,其中每个级别都有唯一的对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4599924/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com