【发布时间】:2021-08-18 00:54:13
【问题描述】:
Rocket 类包含:canCarry(Item item)>检查此物品是否可以携带/carry 使用总重量更新重量。
U2 类是 Rocket 的子类,包含:currentweight, maxWeight=18 吨 项目类别包含:要运输的名称和重量。
在 loadU2 方法中,我试图访问一个项目列表并将其添加到一个火箭中,直到达到该火箭的 maxWeight 。 例如,我有 216 吨的物品要携带返回 12 艘船的清单。
它在 iterator.remove() 行中引发 java.lang.IllegalStateException 错误。我不知道该怎么做,但看起来它不允许我在迭代时删除项目。
public ArrayList<Rocket> loadU2(ArrayList<Item> loadItems){
//list of ships
ArrayList<Rocket> U2Ships = new ArrayList<Rocket>();
for(Iterator<Item> iterator = loadItems.iterator(); iterator.hasNext();) {
//create a new ship
Rocket tempShip = new U2();
Item tempItem = iterator.next();
//loop over items check if it can be filled then remove the item that was filled.
while(tempShip.currentWeight<tempShip.weightLimit) {
if(tempShip.canCarry(tempItem)){
tempShip.carry(tempItem);
iterator.remove();
}
}
U2Ships.add(tempShip);
}
return U2Ships;
}
Exception in thread "main" java.lang.IllegalStateException
at java.base/java.util.ArrayList$Itr.remove(ArrayList.java:980)
at Simulation.loadU1(Simulation.java:35)
at Main.main(Main.java:14)
代码执行的简化示例: 假设每艘船的 maxWeight = 11 吨 ArrayList loadItems = [3,5,5,8,1,2,3,5] 吨
- Ship[1]=[3,5,1,2]
- new list to iterate over >> [5,8,3,5]
- Ship[2]=[5,3]
- new list to iterate over >> [8,5]
- Ship[3]=[8]
- new list to iterate over >> [5]
- Ship[4]=[5]
【问题讨论】:
-
您有一个
while循环,您可能会多次调用iterator.remove()。这是不可能的,你只能调用一次。一旦它被“删除”,你就不能再次删除它,它已经消失了。
标签: java illegalstateexception