我有一个奇怪的问题,我知道这个工作,但这次我想用数组列表来做。这是问题所在: 我有一棵员工树。员工是一个简单的类(在为该员工工作的员工列表下):
class Employee
{
String name;
ArrayList<Employee> under = new ArrayList<Employee>();
//fire function
}
我的任务是以递归方式解雇所有没有员工的员工。我知道如何使用自定义列表数据结构,但我想用数组列表来做。到目前为止,这是我的代码:
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;
}
但是这段代码的问题在于,当我删除 under.remove(x)时, under.size()变小,索引搞砸了。在每次 under.remove(x)之后,我尝试设置 x = 0 ,但它没有完全正确。还有一名员工离开了。任何具有数组列表结构的解决方案?
答案 0 :(得分:4)
这是删除或删除的典型问题。
您必须向后遍历列表。这样,当您删除元素时,不会跳过其他元素或超过列表的末尾。
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;
}
答案 1 :(得分:2)
尝试使用迭代器。你只需要在迭代器上使用.next()
继续遍历它,每当你找到一个没有雇员的人时,你就调用.remove()
(在迭代器上),这将删除迭代器给出的最后一个元素你。
答案 2 :(得分:0)
这就是Iterator有remove()方法的原因。查找Collection的iterator()调用并在for循环中使用它。