iterator.remove() 中的 java.lang.IllegalStateException

问题描述

Rocket 类包含: canCarry(Item item)>检查这个物品是否可以携带/carry 用总重量更新重量。

U2 类是 Rocket 的子类,包含:currentweightma​​xWeight=18 吨 物品类别包含:要运送的名称和重量。

在方法 loadU2 中,我试图访问项目列表并将其添加到一枚火箭中,直到达到该火箭的 ma​​xWeight例如,我要携带 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)

代码正在做什么的简化示例: 假设每艘船的 ma​​xWeight = 11 吨 ArrayList loadItems = [3,5,8,1,2,3,5] 吨

 - Ship[1]=[3,2]
 - new list to iterate over >> [5,5]
 - Ship[2]=[5,3]
 - new list to iterate over >> [8,5]
 - Ship[3]=[8]
 - new list to iterate over >> [5]
 - Ship[4]=[5]

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)