Generate set of unique random numbers in Java

前端 未结 4 985
萌比男神i
萌比男神i 2020-12-03 19:19

I want to create 10 random numbers in the range 0-500. But the problem is that I want those numbers to be unique. For 2 random numbers i could create something as the follow

4条回答
  •  天命终不由人
    2020-12-03 19:47

    Java Collections has a shuffle method. You can put your numbers into an ArrayList and then shuffle its content. If the ArrayList contains n numbers, calling the shuffle method, would give you the same ArrayList containing n numbers but arranged randomly.

    for(int i=0;i<10;i++){
    list.add(i);  // list contains: [0,1,2,3,4,5,6,7,8,9]
    }
    Collections.shuffle(list);// list now contains: [0, 9, 3, 1, 5, 8, 7, 2, 6, 4]
    

提交回复
热议问题