Sagar Nair
Sagar Nair

Reputation: 107

How to remove an element from a Set based on a property value?

I have a static List<Set<Cards>> allcards in a class. The card object has 2 variables which are, String suit and int value. I am creating a set of 52 cards and I am initializing a list of 8 such Sets in the above static parameter.

I pick one set from the list and remove one card from the set. Now if I check the list to see if it has been deleted it does not reflect the removal of my card object from the set.

how do I remove a card from my List<Set<Cards>> variable such that it reflect those changes when I use the variable elsewhere.

public class Test {
  static Shoe shoe = new Shoe();
  static List < Set < Card >> listofdecks;

  public static void main(String[] args) {
    int count = 0;
    listofdecks = new ArrayList < > (shoe.getDecklist());

    for (Set < Card > cards: listofdecks)
      for (Card c: cards)
        count++;
    System.out.println(count);

    listofdecks.get(0).remove(0);

    count = 0;
    for (Set < Card > cards: listofdecks)
      for (Card c: cards)
        count++;

    System.out.println(count);

  }
}

 

public class Shoe {


  private static Deck deck;
  private static List < Set < Card >> decklist;


  public Shoe() {
    setDecklist();
  }
  public static void setDecklist(List < Set < Card >> decklist) {
    Shoe.decklist = decklist;
  }

  public static Deck getDeck() {
    return deck;
  }

  public static void setDeck(Deck deck) {
    Shoe.deck = deck;
  }

  public static List < Set < Card >> getDecklist() {
    return decklist;
  }

  public static void setDecklist() {
    decklist = new ArrayList < > ();
    deck = new Deck();
    for (int i = 0; i < 8; i++)
      decklist.add(Deck.getNewDeck());
  }

}

Upvotes: 0

Views: 1148

Answers (2)

tj9017
tj9017

Reputation: 1

As dehasi mentioned the remove function of java set takes an object which is to be removed. Though you cannot remove the object while iterating, but you can remove the object by using iterator for both list and set.

Upvotes: 0

dehasi
dehasi

Reputation: 2773

When you use listofdecks.get(0).remove(0); is calls boolean remove(Object o); from Set<> interface. Which meant that you try to remove Integer from the set of Cards. That's why nothing happens.

Upvotes: 2

Related Questions