Home > Java > javaTutorial > body text

How Can I Generate Non-Repeating Random Numbers in Java?

Mary-Kate Olsen
Release: 2024-11-09 10:01:02
Original
756 people have browsed it

How Can I Generate Non-Repeating Random Numbers in Java?

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

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:

  1. Create an array of numbers (Integer[] arr).
  2. Use Collections.shuffle(Arrays.asList(arr)) to randomize the order of elements in the array.
  3. The randomized array now contains unique numbers due to the shuffling process.

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template