Home > Java > javaTutorial > body text

How to Generate Non-Repeating Random Numbers in Java?

DDD
Release: 2024-11-06 10:19:02
Original
965 people have browsed it

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));
Copy after login

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));
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!