如何打乱一个顺序的数组,其实集合的帮助类Collection就有现成的方法可用,而且效率还蛮高的,总比自定义随机数等等方法要好很多。其实乱序就这么简单,步骤如下:
1. 将一个顺序排列的数组添加到集合中
2. 可以用集合帮助类Collections的shuffle()方法
3. 用hasNext()、next()方法遍历输入集合
1 /** 2 * 随即打乱一个顺序de数组 3 */ 4 import java.util.ArrayList; 5 import java.util.Collections; 6 import java.util.Iterator; 7 import java.util.List; 8 9 10 public class Shuffle { 11 12 public static void main(String[] args) { 13 shuffle(); 14 } 15 16 public static void shuffle(){ 17 int[] x = {1,2,3,4,5,6,7,8,9}; 18 List list = new ArrayList(); 19 for(int i = 0;i < x.length;i++){ 20 System.out.print(x[i]+", "); 21 list.add(x[i]); 22 } 23 System.out.println(); 24 25 Collections.shuffle(list); 26 27 Iterator ite = list.iterator(); 28 while(ite.hasNext()){ 29 System.out.print(ite.next().toString()+", "); 30 } 31 } 32 }