List<Integer> list 為不重復的數字集合,例如:1,2,3,4,5,6,7,8,9,10
從中隨機獲取不重復的6個數。代碼如下。
1 List<Integer> list = new ArrayList<Integer>(); 2 for(int i=0;i<30;i++){ 3 list.add(i); 4 } 5 6 for(int i = 0;i<6;i++){ 7 //顯示數字並將其從列表中刪除,從而實現不重復. 8 System.out.println(list.remove(new Random().nextInt(list.size()))); 9 }
最后輸出結果如下:29、4、11、0、20、9

