所以我为我的泛型树和随之而来的 Node 类创建了一个类。这些类如下:
public class DirectoryTree<E> implements Serializable {
protected Node<E> root;
protected Node<E> child;
public DirectoryTree() {
root = null;
}//end constructor
protected DirectoryTree(Node<E> root) {
this.root = root;
}
public boolean isLeaf() {
return root.children == null;
}
public DirectoryTree<E> getTree() {
if (root != null) {
return new DirectoryTree<E>(root);
}//end if
else {
return null;
}//end else
}
public Node<E> getRoot() {
return root;
}
public Node<E> getChild() {
return child;
}
public String toString() {
return null;
}//end toString()
}
class Node<E> implements Serializable {
protected Node<E> parent;
protected E data;
protected ArrayList<Node<E>> children;
public Node(E data) {
this.data = data;
children = new ArrayList<Node<E>>();
}
public Node<E> getParent() {
return parent;
}
public ArrayList<Node<E>> getChildren() {
return this.children;
}
public int getNumberOfChildren() {
return getChildren().size();
}
public boolean hasChildren() {
return getChildren().size() > 0;
}
public void addChild(Node<E> child) {
int counter = 0;
for (int i = 0; i < children.size(); i++) {
if (child == children.get(i)) {
System.out.println("directory exists");
counter++;
}
}
if (counter == 0) {
children.add(child);
} else {
}
}
public E getData() {
return this.data;
}
public String toString() {
return data.toString();
}
}
我想知道我的 2 个类是否为通用树正确设置。另外,我甚至不确定如何将此树实现到程序中。 我的程序应该是一个创建目录和文件并将它们放在树中的程序。 我的根目录必须命名为/。 到目前为止,我的主要课程是(我刚刚开始):
public class Driver {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Welcome to Fake Unix");
System.out.print("$");
File f = new File("//");
String input = in.nextLine();
DirectoryTree tree = new DirectoryTree(new Node<File>(f));
while (!input.equalsIgnoreCase("exit")) {
String[] command = input.split(" ");
if (command[0].equals("mkdir") && command[1].equals("-p") && command.length == 3) {
File f1 = new File(command[2]);
tree.root.addChild(new Node<File>(f1));
System.out.println("complete");
}//end if
if (input.equals("tree")) {
System.out.println(tree.toString());
}
System.out.print("$");
input = in.nextLine();
}//end while
}//end main
}//end class
所以我基本上要问的是我的方法在我的树和节点类中看起来是否正确,以及我是否朝着在主类中实现它们的正确方向前进。 我是否正确创建了目录或语法错误?
谢谢。
我假设您希望在文件系统上创建目录。对 javadocs File
的一些挖掘表明您需要为要添加的每个目录调用file.mkdir()
。
就您的课程而言:
- 我认为
DirectoryTree
protected Node<E> child
没有任何用处.您有根,如果这是树将要保存的内容,您可以通过该节点导航到任何子节点。 - 您目前无法在
Node
中设置protected Node<E> parent
。如果您需要从子元素向上导航树,那将很有用 - 您基本上需要实现一个双向链表 - 不应直接从
DirectoryTree
访问Node
的成员变量(请参阅isLeaf()
方法)。在Node
上使用吸气剂,如Node#getChildren()