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

0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 :)
That's a separate question and should be asked elsewhere, however you could look at this question for your answer
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.