Java - 多次从 ArrayList 中删除时出错。(非法状态异常)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13539716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Error when removing from an ArrayList more than once. (IllegalStateException)
提问by AppleDash
I've been googling around for quite a bit, and can't seem to find a solution. What have I done wrong here? My problem is in the title. Here is the exception I get:
我已经在谷歌上搜索了很长时间,似乎找不到解决方案。我在这里做错了什么?我的问题出在标题上。这是我得到的例外:
java.lang.IllegalStateException
at java.util.ArrayList$Itr.remove(Unknown Source)
at me.herp.derp.client.Config.updateItem(Config.java:24)
at me.herp.derp.client.Commands.parseCommand(Commands.java:23)
at me.herp.derp.client.ChatCommands.handleChatcommand(ChatCommands.java:29)
at net.minecraft.src.EntityClientPlayerMP.sendChatMessage(EntityClientPlayerMP.java:171)
at net.minecraft.src.GuiChat.keyTyped(GuiChat.java:104)
at net.minecraft.src.GuiScreen.handleKeyboardInput(GuiScreen.java:227)
at net.minecraft.src.GuiScreen.handleInput(GuiScreen.java:176)
at net.minecraft.client.Minecraft.runTick(Minecraft.java:1494)
at net.minecraft.client.Minecraft.runGameLoop(Minecraft.java:843)
at net.minecraft.client.Minecraft.run(Minecraft.java:768)
at java.lang.Thread.run(Unknown Source)
And here is my code:
这是我的代码:
public static void updateItem(String item, String value)
{
if (!hasValue(item))
{
addItem(item, value);
return;
}
for (ConfigItem c : configItems)
{
if (c.ITEM.equals(item))
{
configItems.iterator().remove();
break;
}
}
ConfigFile.saveConfig();
}
回答by bellum
Your iterator wasn't initialized properly (next()
was not called). I suggest to write this code like this:
您的迭代器未正确初始化(next()
未调用)。我建议这样写这段代码:
Iterator<ConfigItem> it = configItems.iterator();
while(it.hasNext()){
ConfigItem c = it.next();
if (c.ITEM.equals(item))
{
it.remove();
break;
}
}
回答by Evgeniy Dorofeev
You can call Iterator.remove() only after Iterator.next(). Try this:
您只能在 Iterator.next() 之后调用 Iterator.remove()。试试这个:
Iterator<ConfigItem> i = configItems.iterator();
while(i.hasNext()) {
ConfigItem next = i.next();
if (next.equals(item))
{
i.remove();
break;
}