0

I have a strange problem to which I know the work around but I want to do it with array list this time. Here is the problem: I have a tree of employees. Employee is a simple class (under is list of employees that work for this employee) :

class Employee
{
    String name;
    ArrayList<Employee> under = new ArrayList<Employee>();

    //fire function
}

My task is to recursively fire all the employees which do not have employees under them. I know how to this with work around with custom made list data structure but I want to do it with array list. Here is my code so far:

public boolean Fire()
{
    if (under.isEmpty())
        return true;
    else
    {
        for (int x = 0; x < under.size(); x ++)
        {
             if (under.get(x).Fire())
                 under.remove(x);

        }

    }

    return false;
}

But problem for this code is that when I remove under.remove(x) the under.size() gets smaller and indexes get messed up. I tried to set x = 0, after every under.remove(x) but it did not do exactly right. One employee to much still left. Any solutions with array list structure?

3 Answers 3

5

This is a classic problem with removal or deletion.

You have to iterate backwards through the List. That way, when you remove an element, you don't skip other elements or go past the end of the List.

public boolean Fire()
{
    if (under.isEmpty())
        return true;
    else
    {
        for (int x = under.size() - 1; x >= 0; x--)
        {
             if (under.get(x).Fire())
                 under.remove(x);

        }

    }

    return false;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I tend to remember problems that bite me in the rear. :-)
2

Try using an iterator. You just keep traversing it using .next() on the iterator and whenever you find someone that doesn't have employees under him, you call .remove() (on the iterator) which will remove the last element that the iterator gave you.

Comments

0

That's why Iterator has remove() method. Look up Collection's iterator() call and use it in your for loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.