2011-11-08 438 views
0

我正在试图与GUI的Java应用程序。 我写,我不想让用户更改一些数据并保存在一个文本文件,这些变化的代码。这样做,我想删除从列表改变了旧的数据,然后用最后change.if改写新的数据我很想念你想看到任何类之前,请告诉我,我就会把它放到网上尽可能快java.util.ConcurrentModificationException异常错误

这是我

​​

这是SaveOnFile方法: 公共无效SaveOnFile(){

String scoresInString; 
    FileWriter fw; 
    try { 

     fw = new FileWriter("footBall"); 

     for (Competitors C : CompetitorsList) { 
      if (C instanceof footBall) { 
       footBall Scores = new footBall(); 
       scoresInString = Scores.returnScoreAsString(C.scores); 
       fw.write(C.playerNumber + ", " + C.name.getFullName() 
         + ", " + C.level + ", " + scoresInString + "," 
         + ((footBall) C).footSize() + "\n"); 
       fw.write("\r\n"); 
      } 

     } 

     fw.close(); 

    } 
    // message and stop if file not found 
    catch (FileNotFoundException fnf) { 
     System.out.println("File not found "); 
     System.exit(0); 
    } 
    // stack trace here because we don't expect to come here 
    catch (IOException ioe) { 
     ioe.printStackTrace(); 
     System.exit(1); 
    } 
} 

回答

1

调用remove()对集合无效所有活动的迭代器。相反,你必须使用Iterator.remove()方法:

for(Iterator<Competitors> it = CompetitorsList.iterator(); it.hasNext();) { 
    Competitors C = it.next(); 
    if(C instanceof ...) { 
     if(C.getPlayerNumberAsString().equals(Number)) 
      it.remove(); 
    ... 

这样,迭代器()知道如何收集的变化,否则是不可能的,因为ArrayList中不跟踪它生成的迭代器。

+0

感谢您的快速回放,我还有一个问题,如果你能帮助我。写文件有它的空间,我不想有什么办法来控制? –

1

另外,如果你想使用相同的“FOR-NEXT”语法和不会改变的迭代器语法,收集所有的对象被删除到一个临时的集合。例如

ArrayList<Competitors> removeThese = new ArrayList<Competitors>(); 
for (Competitors C : CompetitorsList) { 
    if (wantToRemove(C)) // your number logic goes here... 
     removeThese.add(C); 
} 
CompetitorsList.removeAll(removeThese);