歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java基礎之隨機打亂一個順序數組

Java基礎之隨機打亂一個順序數組

日期:2017/3/1 11:15:01   编辑:Linux編程

如何打亂一個順序的數組,其實集合的幫助類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. public class Shuffle {
  9. public static void main(String[] args) {
  10. shuffle();
  11. }
  12. public static void shuffle(){
  13. int[] x = {1,2,3,4,5,6,7,8,9};
  14. List list = new ArrayList();
  15. for(int i = 0;i < x.length;i++){
  16. System.out.print(x[i]+", ");
  17. list.add(x[i]);
  18. }
  19. System.out.println();
  20. Collections.shuffle(list);
  21. Iterator ite = list.iterator();
  22. while(ite.hasNext()){
  23. System.out.print(ite.next().toString()+", ");
  24. }
  25. }
  26. }
Copyright © Linux教程網 All Rights Reserved