我有两个不同的ArrayList
情况下,Container
类型之一,String
类型之一。第一个是一个国家的“禁用物品”(字符串)清单,另一个是船上的集装箱清单。船在全国各地旅行,并在集装箱内搜索被禁货物。如果容器contains
被禁止的货物,该容器应该被删除/删除。搜索值的一个ArrayList在另一个ArrayList的
public Customs(String country)
{
countryName = country;
bannedGoods = new ArrayList<String>();
}
public Ship(String n, double weight)
{
emptyWeight = totalWeight = weight;
name = n;
containers = new ArrayList<Container>();
}
我已经在船舶类去除容器的方法:
public void removeContainer(int i)
{
if(i >= 0 && i < containers.size()) {
Container r = containers.remove(i);
totalWeight = totalWeight - r.getWeight();
}
}
我想创建一个方法inspect
船上的容器。我想为每个数组使用两个for-loop,但我似乎无法正确使用它!有人可以帮我使用两个循环来搜索数组吗?此外,我认为我需要在循环中使用迭代器(特别是remove
函数),但这对我来说也是令人困惑的。迭代器remove
方法应该替换我已经在课堂上写过的方法吗?以下是我有:
public void inspect(Ship ship)
{
for (String good : bannedGoods) {
for (String con : containers) {
if (con.contains(good) {
container.remove();
}
}
}
这里是我尝试在迭代器:
for(String good : bannedGoods) {
Iterator<String> it = ship.containers.iterator();
while (it.hasNext())
if (ship.contains(good))
it.remove();
}
'containers'是'Container'对象,而不是字符串列表。另外'inspect'大概是'Customs'的一个实例方法,所以它可以直接访问'bannedGoods'列表。 – nbrooks
OP已经写了这样的第一行:'我有两个不同的ArrayLists相同类型的字符串' –
看来,第二个列表是在'容器'内。查看ship构造函数,'containers = new ArrayList();'。 –
nbrooks