我正在尝试用GUI创建一个java应用程序。 我正在编写一个代码,我想让用户更改一些数据并将这些更改保存在文本文件中。在这之前我想删除从列表中更改的旧数据,然后用最后一次更改重写新数据。如果我想错过任何你想看的课,请告诉我,我会尽快将它放在网上< / p>
这是我的
public void saveChanges(footBall Player, String name, String level,
int[] scores, int footSize) {
try {
if (CompetitorsList.size() != 0) {
for (Competitors C : CompetitorsList) {
if (C instanceof footBall) {
String Number = Player.playerNumber + "";
if (C.getPlayerNumberAsString().equals(Number)) {
System.out.println("c");
//the error hit me here when i try to remove the object from the list the exception error is java.util.ConcurrentModificationException
CompetitorsList.remove(C);
}
}
}
Name NewName = new Name(name);
System.out.println("Please get in2");
footBall NewPlayer = new footBall(Player.playerNumber, scores,
level, footSize, NewName);
CompetitorsList.add(NewPlayer);
SaveOnFile();
} else {
System.out.println("No List");
}
} catch (Exception ex) {
System.out.print("testing4");
System.out.print("something wrong" + ex);
}
}
这是SaveOnFile方法: public void 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);
}
}
答案 0 :(得分: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();
...
这样,iterator()知道集合是如何更改的,否则将无法实现,因为ArrayList不会跟踪它生成的迭代器。
答案 1 :(得分:1)
或者,如果要使用相同的“for-next”语法而不是更改为Iterator语法,请将要删除的所有对象收集到临时集合中。 e.g。
ArrayList<Competitors> removeThese = new ArrayList<Competitors>();
for (Competitors C : CompetitorsList) {
if (wantToRemove(C)) // your number logic goes here...
removeThese.add(C);
}
CompetitorsList.removeAll(removeThese);