I am trying to write a recursive method that searches through a list of IData objects and returns a specific implementation. The list contains objects that implements the interface IData.
There are two implementations of this interface:
1) DataImpl
2) DataContainerImpl
The DataContainerImpl has a:
List<IData> children;
so it can hold nested DataContainerImpl elements or just plain DataImpl’s. Here is what I do:
public static DataContainerImpl findDataContainerWithName(Collection<IData> elements, String name) {
for (IData element : elements) {
if (element instanceof DataContainerImpl) {
DataContainerImpl container = (DataContainerImpl) element;
if (container.getName().equals(name)) {
return container ;
}
container = findDataContainerWithName(container.getChildren(), name);
if (container != null) {
return container ;
}
}
}
return null;
}
Not exactly sure what you are doing here, but calling “findContainerByName()” recursively without a “return” in front of it wont do you any good.
The recursive call will return , but then the call will drop to the bottom and return null.
For example, if your list contained just 1 DataContainerImpl whose name did not match the name you called the method with, but it contains inside it a list with again just 1 DataImpl, you will still get null back. Is this what you want?