Java Approach to Generating Non-Repeating Random Numbers
Creating a set of unique random numbers in Java can be a challenge. Consider the following scenario where we need to populate an array with 10,000 non-repeating integers ranging from 0 to 9999.
The following code snippet attempts to address this problem using Java's built-in Random class:
import java.util.Random; public class Sort { public static void main(String[] args) { int[] nums = new int[10000]; Random randomGenerator = new Random(); for (int i = 0; i < nums.length; ++i) { nums[i] = randomGenerator.nextInt(10000); } } }
However, this code may produce duplicate numbers due to the potential for collisions when using the modulo operation to map the random number to the desired range. To ensure unique numbers, we can leverage Java's Collections class.
Solution Using Java Collections.shuffle()
The preferred approach for generating non-repeating random numbers in Java is to utilize the Collections.shuffle() method. Here's how it works:
For instance, the following code snippet demonstrates this method:
public static void main(String[] args) { Integer[] arr = new Integer[1000]; for (int i = 0; i < arr.length; i++) { arr[i] = i; } Collections.shuffle(Arrays.asList(arr)); System.out.println(Arrays.toString(arr)); }
This approach guarantees that each number in the array is unique and meets the requirement of generating non-repeating random numbers.
The above is the detailed content of How Can I Generate Non-Repeating Random Numbers in Java?. For more information, please follow other related articles on the PHP Chinese website!