【发布时间】:2012-03-13 20:05:40
【问题描述】:
我创建了一个类来模拟我正在开发的程序(基于文本的游戏)的文件结构。这是一个简化版:
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);
}
}
如果目录被移动,我仍然需要跟踪对父级的任何更改,但这至少现在有效。
【问题讨论】:
标签: java class parent self-reference