binary101
binary101

Reputation: 1023

Deleting element from ArrayList

I'm trying to copy 'select' elements from hands[1] to hands[0]. I can successfully do this with this code:

       for(Card card : hands[1].cards) {
          if (card.suit().ordinal() == 0){
             hands[0].addSingleCard(card);
             //hands[1].removeSingleCard(card);
             }
       }

Unfortunately, my removeSingleCard method doesn't work how i expected. With it commented out, the for-each loop successfully copies all 'Club' cards from hands[1] to hands[0]. I was hoping the removeSingleCard method would delete each 'Club' card from hands[1] after it was copied.

       public void addSingleCard(Card card){
           if(card!= null){
             cards.add(card);
           }
       }

       public void removeSingleCard(Card c){
           if(c!= null){
             cards.remove(c);
           }
       }

Any ideas why this isn't working?

Upvotes: 1

Views: 161

Answers (2)

Cratylus
Cratylus

Reputation: 54094

I assume that you get a ConcurrentModificationException since you are removing from a collection while you are iterating in the for loop.
You should use iterator.remove

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503984

You can't remove from a collection you're iterating over, other than via the iterator. So you could use:

for (Iterator<Card> iterator = hands[1].cards.iterator();
     iterator.hasNext(); ) {
    Card card = iterator.next();
    if (card.suit().ordinal() == 0) {
        hands[0].addSingleCard(card); // Or hands[0].cards.add(card);
        iterator.remove();
    }
}

Upvotes: 6

Related Questions