2012-11-24 24 views
3

我一直在搜索相当多,似乎无法找到解决方案。我在这里做错了什么?我的问题在标题中。这里是例外,我得到:Java - 多次从ArrayList中删除时出错。 (IllegalStateException)

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) 

这里是我的代码:

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(); 
} 
+2

你不觉得对谷歌,你应该只使用'iterator'遍历列表,如果你想修改它? –

+1

@RohitJain yuo是对的,发布它作为一个答案与一些解释有关它,我相信这将有助于至少OP和我 – Abubakkar

+0

@RohitJain但我**正在**修改它... – AppleDash

回答

12

你的迭代器无法正常初始化(next()不叫)。我建议写这样的代码:

Iterator<ConfigItem> it = configItems.iterator(); 
while(it.hasNext()){ 
    ConfigItem c = it.next(); 
    if (c.ITEM.equals(item)) 
    { 
     it.remove(); 
     break; 
    } 
} 
+0

工作就像一个魅力,非常感谢! – AppleDash

+1

@bellum虽然你显示的代码有效,但你的答案是不正确的,因为for循环中使用的隐藏迭代器和'if“块中使用的迭代器之间没有关系。 'remove'方法失败,因为在迭代器尚未启动时调用它,正如@Evgeniy正确指出的那样。调用'if'中的'configItems.remove(c)'可以获得相同的结果。 – remigio

+0

@remigio你是对的。感谢名单。文本编辑。 – bellum

2

你可以叫Iterator.remove()只Iterator.next后()。试试这个:

Iterator<ConfigItem> i = configItems.iterator(); 
while(i.hasNext()) { 
    ConfigItem next = i.next(); 
    if (next.equals(item)) 
    { 
     i.remove(); 
     break; 
    }