JAVA的Collections类中shuffle的用法

来源:互联网 发布:autodesk 360 mac卸载 编辑:程序博客网 时间:2024/05/16 16:17

就是随机打乱原来的顺序,和洗牌一样。如:

[java] view plain copy
  1. // ShuffleTest.<a href="http://lib.csdn.net/base/javase" class='replace_word' title="Java SE知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Java</a>  
  2.   
  3. import java.util.*;  
  4.   
  5. public class ShuffleTest {  
  6.     public static void main(String[] args) {  
  7.         List<Integer> list = new ArrayList<Integer>();  
  8.         for (int i = 0; i < 10; i++)  
  9.             list.add(new Integer(i));  
  10.         System.out.println("打乱前:");  
  11.         System.out.println(list);  
  12.   
  13.         for (int i = 0; i < 5; i++) {  
  14.             System.out.println("第" + i + "次打乱:");  
  15.             Collections.shuffle(list);  
  16.             System.out.println(list);  
  17.         }  
  18.     }  
  19. }  

输出结果:

打乱前:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
第0次打乱:
[6, 3, 2, 0, 8, 1, 7, 5, 4, 9]
第1次打乱:
[6, 2, 3, 0, 8, 5, 7, 4, 9, 1]
第2次打乱:
[1, 7, 9, 4, 6, 0, 2, 5, 3, 8]
第3次打乱:
[0, 4, 2, 8, 9, 1, 3, 7, 5, 6]
第4次打乱:
[8, 1, 3, 0, 7, 9, 4, 2, 5, 6]

 

摘自:http://topic.csdn.net/u/20080308/17/642f73e3-ff7b-4144-a52b-190a72be1e49.html

0 0