Home > Java > javaTutorial > body text

How to Generate Unique Random Numbers in Java?

Mary-Kate Olsen
Release: 2024-11-09 00:40:02
Original
329 people have browsed it

How to Generate Unique Random Numbers in Java?

Generating Unique Random Numbers in Java

In Java, generating random numbers without repeats can be achieved through various methods. One commonly used approach involves leveraging a hash set to ensure uniqueness.

Optimal Solution

To create a set of non-repeating random numbers in Java, you can utilize the following approach:

import java.util.HashSet;
import java.util.Random;

public class UniqueRandomNumbers {

    public static void main(String[] args) {
        int[] nums = new int[10000];

        // Create a hash set to store unique numbers
        HashSet<Integer> uniqueNumbers = new HashSet<>();

        Random randomGenerator = new Random();

        // Generate random numbers until the set contains 10,000 unique values
        while (uniqueNumbers.size() < nums.length) {
            int randomNumber = randomGenerator.nextInt(10000);

            // Add the random number to the set if it's not already present
            if (!uniqueNumbers.contains(randomNumber)) {
                uniqueNumbers.add(randomNumber);
            }
        }

        // Convert the set into an array
        int[] nonRepeatingNumbers = new int[uniqueNumbers.size()];
        int index = 0;
        for (int number : uniqueNumbers) {
            nonRepeatingNumbers[index] = number;
            index++;
        }

        System.out.println("10,000 unique random numbers: " + Arrays.toString(nonRepeatingNumbers));
    }
}
Copy after login

In this optimized solution:

  1. A hash set uniqueNumbers is initialized to store unique values.
  2. A random number generator randomGenerator is created.
  3. Random numbers are generated within a loop until the set reaches the desired size.
  4. Before adding a random number to the set, its presence is checked to ensure uniqueness.
  5. Once the set contains the desired number of unique values, it is converted into an array nonRepeatingNumbers.

This approach guarantees that all the generated numbers are unique, eliminating the possibility of duplicates.

The above is the detailed content of How to Generate Unique Random Numbers in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!