Generating Unique Random Numbers in Java

后端 未结 21 2609
不思量自难忘°
不思量自难忘° 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:16

    try this out

    public class RandomValueGenerator {
        /**
         * 
         */
        private volatile List previousGenValues = new ArrayList();
    
        public void init() {
            previousGenValues.add(Double.valueOf(0));
        }
    
        public String getNextValue() {
            Random random = new Random();
            double nextValue=0;
            while(previousGenValues.contains(Double.valueOf(nextValue))) {
                nextValue = random.nextDouble();
            }
            previousGenValues.add(Double.valueOf(nextValue));
            return String.valueOf(nextValue);
        }
    }
    

提交回复
热议问题