Reputation: 11
How can I modify an arraylist while iterating over it? I would like answers that only deal with whilst I am iterating it please no answers regarding that I can save it and then modify it.
for (ListIterator<CardGroup> ShortSeqGroupListIterator = ShortSeqGroupList
.listIterator(); ShortSeqGroupListIterator.hasNext();) {
CardGroup ShortSeqGroup = ShortSeqGroupListIterator.next();
System.out.println("Iteration --- "+ShortSeqGroup.getCardList());
for (ListIterator<CardGroup> cardGroupListIterator = this.cardGroupList
.listIterator(); cardGroupListIterator.hasNext();) {
CardGroup cardGroup = cardGroupListIterator.next();
if (cardGroup.getCardGroupType() == CardGroupType.PURESEQUENCE
|| cardGroup.getCardGroupType() == CardGroupType.SHORTSEQUENCE) {
continue;
}
Listindex = cardGroupListIterator.nextIndex() - 1;
listOfIndex.add(Listindex);
cardGroup.setCardGroupType(CardGroupType.NONE);
this.mergeExtraGroups();
}
ShortSeqGroup.setCardGroupType(CardGroupType.NONE);
this.mergeExtraGroups();
this.markSets();
this.markSequences(false);
int PenaltyPointsShSeq = totalPenaltyOfUser(this.cardGroupList);
PenaltyMapShortSeq.put(PenaltyPointsShSeq, this.cardGroupList);
this.cardGroupList = clonedCardGroupList;
System.out.println("&************************&");
this.print();
}
NavigableMap<Integer, List<CardGroup>> descendedPenaltyMapShortSeq=PenaltyMapShortSeq.descendingMap();
System.out.println(descendedPenaltyMapShortSeq.firstKey());
I want to operate on the list and then after saving the operation I need to get the previous state of the list back .. The problem is of course Concurrent modification exception.
The this.cardList
is the one I am operating on and the cloned cardgrouplist
is a copy of it...
The cardGrouplist
1st element again contains:
An arraylist
Upvotes: 0
Views: 504
Reputation: 850
It look messy to modify a collection while iterating. I would suggest you to iterate to collect the list of items to add/delete first. Then, perform add/delete the collected item accordingly.
Upvotes: 0
Reputation: 2947
Don't use an Iterator
, switch it out for a normal for(int i = 0; i < list.length; i++)
loop.
Upvotes: 2