溫馨提示×

如何利用Java children實現(xiàn)數(shù)據(jù)的層級展示

小樊
86
2024-09-07 13:04:43
欄目: 編程語言

在Java中,可以使用樹形結構(Tree)來表示具有層級關系的數(shù)據(jù)。這里是一個簡單的例子,展示了如何使用Java實現(xiàn)數(shù)據(jù)的層級展示。

首先,創(chuàng)建一個表示樹節(jié)點的類Node

public class Node {
    private String name;
    private List<Node> children;

    public Node(String name) {
        this.name = name;
        this.children = new ArrayList<>();
    }

    public void addChild(Node child) {
        children.add(child);
    }

    public String getName() {
        return name;
    }

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

接下來,創(chuàng)建一個方法來遍歷樹并打印層級結構:

public static void printTree(Node node, int level) {
    if (node == null) {
        return;
    }

    // 打印當前節(jié)點的縮進和名稱
    for (int i = 0; i< level; i++) {
        System.out.print("  ");
    }
    System.out.println(node.getName());

    // 遞歸遍歷子節(jié)點
    for (Node child : node.getChildren()) {
        printTree(child, level + 1);
    }
}

最后,創(chuàng)建一個樹并調用printTree方法來展示層級結構:

public static void main(String[] args) {
    Node root = new Node("root");

    Node child1 = new Node("child1");
    Node child2 = new Node("child2");
    Node child3 = new Node("child3");

    root.addChild(child1);
    root.addChild(child2);
    root.addChild(child3);

    Node grandchild1 = new Node("grandchild1");
    Node grandchild2 = new Node("grandchild2");

    child1.addChild(grandchild1);
    child1.addChild(grandchild2);

    printTree(root, 0);
}

運行上述代碼,將會輸出以下層級結構:

root
  child1
    grandchild1
    grandchild2
  child2
  child3

這個例子展示了如何使用Java實現(xiàn)數(shù)據(jù)的層級展示。你可以根據(jù)需要修改Node類以存儲更多的信息,或者調整printTree方法以自定義輸出格式。

0