user11364302
user11364302

Reputation:

How to get all children recursive in arraylist in Java

Im working on a Method which should return an Arraylist with all the Descendants. It almost works, but the first ("highest") Person is always included, but I don't need him. Can anyone improve my code? Thanks

getChildren - return only the Children of a Person

public ArrayList<Person> getDescendants() {
        ArrayList<Person> descendants = new ArrayList<Person>();
        ArrayList<Person> next = this.getChildren();
        if (next.size() != 0) {
            for (int i = 0; i < next.size(); i++) {
                ArrayList<Person> b = next.get(i).getDescendants();
                descendants.addAll(b);
                if (!descendants.contains(this)) {
                    descendants.add(this);
                }
            }
            return descendants;
        } else {
            descendants.add(this);
            return descendants;
        }
    }

Upvotes: 0

Views: 1021

Answers (2)

Code-Apprentice
Code-Apprentice

Reputation: 83527

descendants.add(this);

You are explicitly adding the parent to your descendants list. Don't do that.

Also note that the if statement isn't required. When the length of the list of children is zero, the loop won't iterate at all.

Upvotes: 2

Andreas
Andreas

Reputation: 159106

Your code seems overly complex. Did you mean this?

public ArrayList<Person> getDescendants() {
    ArrayList<Person> descendants = new ArrayList<Person>();
    for (Person child : this.getChildren()) {
        descendants.add(child);
        descendants.addAll(child.getDescendants());
    }
    return descendants;
}

Upvotes: 2

Related Questions