Generating Unique Random Numbers in Java

后端 未结 21 2600
不思量自难忘°
不思量自难忘° 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条回答
  •  臣服心动
    2020-11-21 08:08

    I re-factored Anand's answer to make use not only of the unique properties of a Set but also use the boolean false returned by the set.add() when an add to the set fails.

    import java.util.HashSet;
    import java.util.Random;
    import java.util.Set;
    
    public class randomUniqueNumberGenerator {
    
        public static final int SET_SIZE_REQUIRED = 10;
        public static final int NUMBER_RANGE = 100;
    
        public static void main(String[] args) {
            Random random = new Random();
    
            Set set = new HashSet(SET_SIZE_REQUIRED);
    
            while(set.size()< SET_SIZE_REQUIRED) {
                while (set.add(random.nextInt(NUMBER_RANGE)) != true)
                    ;
            }
            assert set.size() == SET_SIZE_REQUIRED;
            System.out.println(set);
        }
    }
    

提交回复
热议问题