Home  >  Article  >  Java  >  How to Generate Non-Repeating Random Numbers in Java?

How to Generate Non-Repeating Random Numbers in Java?

DDD
DDDOriginal
2024-11-06 10:19:02969browse

How to Generate Non-Repeating Random Numbers in Java?

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!

Statement:
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