Home >Java >javaTutorial >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() <p>In this optimized solution:</p> <ol> <li>A hash set uniqueNumbers is initialized to store unique values.</li> <li>A random number generator randomGenerator is created.</li> <li>Random numbers are generated within a loop until the set reaches the desired size.</li> <li>Before adding a random number to the set, its presence is checked to ensure uniqueness.</li> <li>Once the set contains the desired number of unique values, it is converted into an array nonRepeatingNumbers.</li> </ol> <p>This approach guarantees that all the generated numbers are unique, eliminating the possibility of duplicates.</p></integer>
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!