Generating Unique Random Numbers in Java

后端 未结 21 2606
不思量自难忘°
不思量自难忘° 2020-11-21 07:45

I\'m trying to get random numbers between 0 and 100. But I want them to be unique, not repeated in a sequence. For example if I got 5 numbers, they should be 82,12,53,64,32

21条回答
  •  猫巷女王i
    2020-11-21 07:59

    • Add each number in the range sequentially in a list structure.
    • Shuffle it.
    • Take the first 'n'.

    Here is a simple implementation. This will print 3 unique random numbers from the range 1-10.

    import java.util.ArrayList;
    import java.util.Collections;
    
    public class UniqueRandomNumbers {
    
        public static void main(String[] args) {
            ArrayList list = new ArrayList();
            for (int i=1; i<11; i++) {
                list.add(new Integer(i));
            }
            Collections.shuffle(list);
            for (int i=0; i<3; i++) {
                System.out.println(list.get(i));
            }
        }
    }
    

    The first part of the fix with the original approach, as Mark Byers pointed out in an answer now deleted, is to use only a single Random instance.

    That is what is causing the numbers to be identical. A Random instance is seeded by the current time in milliseconds. For a particular seed value, the 'random' instance will return the exact same sequence of pseudo random numbers.

    NOTE that the public Integer​(int value) constructor is deprecated since Java 9.

    The first for loop can simply be changed to:

    for (int i = 1; i < 11; i++) {
      list.add(i);
    }
    

提交回复
热议问题