Java recursion does not iterate over all top-level elements

I face the problem of recursion I have an object that contains its own list. Each object in the list can save its own list This object represents a tree

Now I want to iterate over all possible objects to find a specific object, but I failed At present, my method does not return to the top level. I don't know how to solve it

method:

private Object selectSpecificItem(TreeObject treeObject) {
    for (TreeObject to : treeObject.getChildren()) {
        Object data = to.getData();
        if (data instanceof PaymentOffice) {
            PaymentOffice po = (PaymentOffice) data;
            if (po.getCode().equals(getModelObject().getLocation())) {
                return to;
            }
        } else if (to.getChildren().length > 0) {
            selectSpecificItem(to);
        }
    }
    return null;
}

Assume the following list structure:

Item1
    - Item1.1
    - Item1.2
    - Item1.3
    - Item1.4
Item2
Item3

Now it iterates over all 1 / 1 X instead of 2 / 3 The item I need to find now is Item3

How do I change recursion to iterate over all elements?

Solution

You ignored the value returned by the recursive call You should check whether the recursive call returns a non null value, and if so, return it

private Object selectSpecificItem(TreeObject treeObject) {
    Object result = null;
    for (TreeObject to : treeObject.getChildren()) {
        Object data = to.getData();
        if (data instanceof PaymentOffice) {
            PaymentOffice po = (PaymentOffice) data;
            if (po.getCode().equals(getModelObject().getLocation())) {
                return to;
            }
        } else if (to.getChildren().length > 0) {
            result = selectSpecificItem(to);
            if (result != null) {
                return result;
            }
        }
    }
    return result;
}

Some people prefer to use a single return statement at the end of a method If you are such a person, you can write:

private Object selectSpecificItem(TreeObject treeObject) {
    Object result = null;
    for (TreeObject to : treeObject.getChildren()) {
        Object data = to.getData();
        if (data instanceof PaymentOffice) {
            PaymentOffice po = (PaymentOffice) data;
            if (po.getCode().equals(getModelObject().getLocation())) {
                result = to;
                break;
            }
        } else if (to.getChildren().length > 0) {
            result = selectSpecificItem(to);
            if (result != null) {
                break;
            }
        }
    }
    return result;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>