0

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

Draken
  • 3,134
  • 13
  • 34
  • 54

2 Answers2

2

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

rorschach
  • 2,871
  • 1
  • 17
  • 20
  • One more thing -->> When i am copying the list I get the same one , i need a new copy with even its contents totally new #branded new :) – user3705056 Sep 14 '16 at 08:23
  • That's a separate question and should be asked elsewhere, however you could look at [this question for your answer](http://stackoverflow.com/questions/715650/how-to-clone-arraylist-and-also-clone-its-contents) – Draken Sep 14 '16 at 08:27
0

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.

Duong Nguyen
  • 830
  • 6
  • 10