I’ve created a class to mimic a file structure for a program (a text-based game) I’m working on. This is a simplified version:
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
}
The structure would be created using something like this (only much, much bigger):
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),
});
And finally, the current directory is tracked in the variable currentDir, and will change arbitrarily based on user input:
Dir currentDir = root.subdir[0].subdir[3].subdir[0];
I want to be able to find the parent object of a given object. In this case, currentDir has a parent named “child3”, which has a parent named “first”, which has a parent named “root”, which doesn’t have a parent. How best to go about that? Also, any tips on a better way to do this are appreciated – I’ve plenty of programming experience, just not a lot in Java.
Edit:
I ended up creating a recursive subroutine, to be run once the directories have been set up:
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);
}
}
I still have to track any changes to the parent if a directory is moved, but this works, for now at least.
You could have a
parentDirreference in eachDirobject.In the constructor of
Diryou’d do something likeI realize that it introduces some redundancy and annoying invariants in your code. I guess the alternative is to have a simple function that recursively finds the parent of a dir-object by searching from the root. Could be done by something like this:
A side-note: I strongly suggest you use empty arrays instead of
nullfor directories that don’t have any children. That avoids a lot of conditional code (if-statements).