在自引用Java类中查找父对象



我创建了一个类来模拟我正在开发的程序(一个基于文本的游戏)的文件结构。这是一个简化版本:

public class Dir {
  public Dir(String name, Dir[] subdirs) {
    this.name = name;
    this.subdirs = subdirs;
  }
  public String name;         //directory name
  public Dir[] subdirs;       //Sub-directories
}

该结构将使用这样的东西创建(只是大得多):

private Dir root = new Dir("root",new Dir[]{
  new Dir("first",new Dir[]{
    new Dir("child1",null),
    new Dir("child2",null),
    new Dir("child3",new Dir[]{
      new Dir("child3-1",null)
    })
  }),
  new Dir("second",null),
});

最后,在变量currentDir中跟踪当前目录,并根据用户输入任意更改:

Dir currentDir = root.subdir[0].subdir[3].subdir[0];

我希望能够找到给定对象的父对象。在这种情况下,currentDir有一个名为"child3"的父级,该父级有一个名称为"first"的父代,该父代有一个没有父级的名称为"root"。如何最好地做到这一点?此外,任何关于更好的方法的提示都会受到赞赏——我有很多编程经验,只是在Java方面不多。

编辑:

我最终创建了一个递归子程序,在目录设置好后运行:

private void setParent(Dir thisDir) {
  //Loop through every subdir
  for(Dir tmp : thisDir.subdirs) {
    //set this as the parent on each sub-dir
    tmp.parent = thisDir;
    //then call setParent on each sub-dir
    setParent(tmp);
  }
}

如果目录被移动,我仍然需要跟踪对父目录的任何更改,但至少目前这样做是有效的。

在每个Dir对象中都可以有一个parentDir引用。

Dir的构造函数中,您可以执行类似的操作

for (Dir subdir : subdirs)
    subdir.parent = this;

我意识到它在代码中引入了一些冗余和烦人的不变量。我想另一种选择是使用一个简单的函数,通过从根目录搜索递归地找到dir对象的父对象。可以这样做:

Dir findParent(Dir root, Dir d) {
    if (Arrays.asList(subdirs).contains(d))
        return this;
    for (Dir subdir : subdirs) {
        Dir parent = findParent(subdir, d);
        if (parent != null)
            return parent;
    }
    return null;
}

附带说明:对于没有任何子级的目录,我强烈建议您使用空数组,而不是null。这避免了大量的条件代码(if语句)。

向Dir类添加一个父引用并爬上树:

public class Dir {
  public Dir(String name, Dir parent, Dir[] subdirs) {
    this.name = name;
    this.subdirs = subdirs;
    this.parent = parent;
  }
  public String name;         //directory name
  public Dir[] subdirs;       //Sub-directories
  public Dir parent;
}

但是你的一行实例化不起作用。。。

按照aioobe的建议,为每个Dir存储parentDir,每次需要都搜索父级(非常糟糕),或者使用现有的库,如类路径资源管理器。这可能正是你所需要的。

JDK7还有一些更高级的文件处理功能,所以如果Dir()结构反映了实际的文件系统,您甚至可能不需要自己实现它。

最新更新