Course contentsShow
← Java
Lesson 1232 of 2,87028. Collections Utility ClassFree lesson

Providing a Custom Random Source to shuffle

Control randomness by passing a Random or SecureRandom instance to shuffle for reproducible or secure shuffles.

Providing a Custom Random Source to shuffle

What you'll learn: How to pass your own Random or SecureRandom instance to Collections.shuffle() to control the randomness—making shuffles either reproducible or cryptographically secure.


Why Control the Random Source?

By default, Collections.shuffle() uses Java's built-in random number generator. But sometimes you want more control:

  • Reproducibility: Use the same random "seed" to get identical shuffles every time (great for testing or debugging)
  • Security: Use SecureRandom for cryptographically strong randomness when shuffling sensitive data

Think of it like controlling which dice you roll—a weighted die always produces the same pattern, while a casino-grade die is truly unpredictable.


The Overloaded shuffle Method

Collections.shuffle() has a second version that accepts a Random object:

import java.util.*;

public class CustomShuffleDemo {
    public static void main(String[] args) {
        List<String> deck = new ArrayList<>(Arrays.asList("A", "2", "3", "4", "5"));
        
        // Reproducible shuffle with seeded Random
        Random seededRandom = new Random(42); // Same seed = same shuffle
        Collections.shuffle(deck, seededRandom);
        System.out.println("Seeded shuffle: " + deck);
        
        // Secure shuffle with SecureRandom
        List<String> sensitive = new ArrayList<>(Arrays.asList("PIN1", "PIN2", "PIN3"));
        SecureRandom secureRandom = new SecureRandom();
        Collections.shuffle(sensitive, secureRandom);
        System.out.println("Secure shuffle: " + sensitive);
    }
}

Using new Random(42) with the same seed always produces the same "random" sequence—perfect for unit tests. Using SecureRandom provides unpredictable, cryptography-grade randomness for security-sensitive applications.


Key Takeaway: Pass a Random instance with a fixed seed to shuffle() for reproducible shuffles in tests, or use SecureRandom when cryptographic randomness is required for security.