user3705056
user3705056

Reputation: 11

Modifying an Array list while I am iterating over it

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

Answers (2)

Duong Nguyen
Duong Nguyen

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

rorschach
rorschach

Reputation: 2947

Don't use an Iterator, switch it out for a normal for(int i = 0; i < list.length; i++) loop.

Upvotes: 2

Related Questions