1

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?

1
  • The card.suit().ordinal() == 0 test is unidiomatic. Just use card.suit() == Suit.CLUBS. If you defined your suits in a different order, use the 0th element in the enum. Any use of Enum.ordinal() should arouse suspicion. Commented Apr 25, 2013 at 5:50

2 Answers 2

6

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();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ah nice :) This is awesome. Its exactly what i was trying to achieve. Thanks so much. I definitely need to remember this :D
2

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

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.