Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shuffle an object array in Java

I want to implement a poker game in Java. So I made a card class and created 52 card objects and put them into a array. This array is the card deck.

How would I randomly shuffle this array of objects? Is there an inbuilt method or any other way?

like image 984
Daybreaker Avatar asked Sep 04 '25 01:09

Daybreaker


2 Answers

Use ArrayList instead and use Collections.shuffle()

Collections.shuffle(yourListInstance);
like image 60
jmj Avatar answered Sep 07 '25 06:09

jmj


I've modified the top answer from "Random shuffling of an array" to work for an array of Card objects. I simply changed int[] arCard[] ar, and int a = ar[index]Card a = ar[index]

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

// Implementing Fisher–Yates shuffle
static void shuffleArray(Card[] ar)
{
  // If running on Java 6 or older, use `new Random()` on RHS here
  Random rnd = ThreadLocalRandom.current();
  for (int i = ar.length - 1; i > 0; i--)
  {
    int index = rnd.nextInt(i + 1);
    // Simple swap
    Card a = ar[index];
    ar[index] = ar[i];
    ar[i] = a;
  }
}
like image 23
Stevoisiak Avatar answered Sep 07 '25 05:09

Stevoisiak