Reputation: 1
I am new to Java so any advice would be really appreciated.
I have a tree-like File System with files and directories. I want to find a Directory by its name.
Component is an interface and both File and Directory implement it.
I wrote this method in the class Directory in order to find a Directory named name.
public Directory getDir(String name) {
Iterator<Component> iterator = (Iterator<Component>)components.iterator();
Component component = null;
while(iterator.hasNext()) {
component = iterator.next();
if(component instanceof Directory) {
if(component.getName().equals(name))
return (Directory) component;
else component.getDir(name);
}
}
return null;
}
Somehow, this method won't stop after finding my Directory.
I tried writing "return component.getDir(name)
" but it doesn't help. It won't search in every component of my node, just in the first one.
What am I doing wrong?
Please help me.
Thank you
Upvotes: 0
Views: 68
Reputation: 102
Looks like your line:
else component.getDir(name)
is not checked for a return value. No matter whether that recursive call returns a found directory or null (nothing found), the next thing will be another round in the loop.
Just check whether it returns not null, then return this again.
Upvotes: 1