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)); } }
In this optimized solution:
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!