user9245434
user9245434

Reputation:

Picking a random element from an arraylist and removing it from the list in Java

I am working on a command line type of program that would allow you to play solitaire. I currently have class Deck and class Card. In class Deck i have an ArrayList and two methods - one that creates a deck and one that shuffles it. I need to create a method that deals a card - meaning a method that would pick a random element from an ArrayList and it is gonna erase it from the ArrayList. When a card is dealt it is not in the ArrayList anymore, i believe. Here is the code in my Deck class:

public class Deck {
   private ArrayList deck = new ArrayList < Card > ();
   private Random randomGenerator;

}

public Deck() {
 for (Suit s: Suit.values())
  for (Numbers n: Numbers.values()) {
   Card c1 = new Card(n, s);
   deck.add(c1);
   System.out.println(deck);
  }
}
private void printAll() {}
public void shuffle() {
 Collections.shuffle(deck);
}

I'm really having a hard time with creating a method that would erase the dealt element, what i have done so far is pretty much based on the answers of this problem but it is not quite what i need. Retrieving a random item from ArrayList

public Card deal(deck) {
    Random rand = new Random();
    Card dealtCard = rand.deck();
    return dealtCard;
}

Could anyone provide any guidance for me on this method? Please and thank you

Upvotes: 0

Views: 814

Answers (2)

sprinter
sprinter

Reputation: 27946

Really the entire point of shuffling the deck is to allow you to deal from the top of the deck and get random cards each time. So if the Deck class has:

private final List<Card> cards = new ArrayList<>();

And you have called Collections.shuffle(cards) then all you need to do to get the top card in the deck is:

public Card deal() {
    return cards.remove(0);
}

You should also have an isEmpty method so that the caller can make sure there are cards left in the deck before calling deal. That's better coding practice than catching the IndexOutOfBoundsException.

Upvotes: 3

Sudhindra
Sudhindra

Reputation: 11

You could use something like this

Random rand = new Random();

int randomElement = givenList.get(rand.nextInt(givenList.size()));

I think this link might be useful http://www.baeldung.com/java-random-list-element

Upvotes: -1

Related Questions