Generating Non-Repeating Random Numbers in Java
In Java, generating random numbers that do not repeat can be achieved using the following steps:
Problem:
You wish to create an array with non-repeating random integers from a specific range.
Solution:
To generate a set of random numbers without duplicates in Java, utilize the Collections.shuffle() method.
Code:
Integer[] arr = {...}; Collections.shuffle(Arrays.asList(arr));
For instance:
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)); }
The Collections.shuffle() method effectively shuffles the elements within the specified list, essentially randomizing their order and eliminating any duplicates. The resulting array, arr, will feature unique and random integers within the defined range.
The above is the detailed content of How to Generate Non-Repeating Random Numbers in Java?. For more information, please follow other related articles on the PHP Chinese website!