java怎么组合成这样的多层级数据
时间: 2023-12-01 19:04:28 浏览: 31
在 Java 中,你可以使用类和对象的方式来表示多层级数据结构。以下是一个示例代码,演示如何使用 Java 组合成多层级数据:
```java
import java.util.ArrayList;
import java.util.List;
public class Node {
private String name;
private String value;
private List<Node> children;
public Node(String name, String value) {
this.name = name;
this.value = value;
this.children = new ArrayList<>();
}
public void addChild(Node child) {
children.add(child);
}
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public List<Node> getChildren() {
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
}
public class Main {
public static void main(String[] args) {
Node node1 = new Node("节点1", "1");
Node node1_1 = new Node("节点1-1", "1-1");
Node node1_1_1 = new Node("节点1-1-1", "1-1-1");
Node node1_1_2 = new Node("节点1-1-2", "1-1-2");
node1_1.addChild(node1_1_1);
node1_1.addChild(node1_1_2);
node1.addChild(node1_1);
node1.addChild(new Node("节点1-2", "1-2"));
Node node2 = new Node("节点2", "2");
node2.addChild(new Node("节点2-1", "2-1"));
node2.addChild(new Node("节点2-2", "2-2"));
List<Node> data = new ArrayList<>();
data.add(node1);
data.add(node2);
// 使用多层级数据
// ...
}
}
```
在上述示例中,我们创建了一个 `Node` 类来表示每个节点,包含名称 `name`、值 `value` 和子节点列表 `children`。通过调用 `addChild()` 方法可以向父节点添加子节点。
在 `Main` 类的 `main` 方法中,我们创建了一个多层级的数据结构,并将其存储在一个 `List<Node>` 中。你可以根据需要构建更复杂的多层级数据结构。
请注意,这只是一个简单的示例,你可以根据实际需求对 `Node` 类进行扩展,添加更多属性和方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)