zoukankan      html  css  js  c++  java
  • java Collection.shuffle()随机打乱一个顺序数组

    如何打乱一个顺序的数组,其实集合的帮助类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 }  
  • 相关阅读:
    第二章整理
    汇编实验二
    汇编实验一
    第一章整理
    第一部分 | 第1章 —— Hello Cocos2d-x
    返回 *this 的成员函数以及 const重载
    C++中的const
    680. Valid Palindrome II
    字典树
    单调队列
  • 原文地址:https://www.cnblogs.com/daohangtaiqian/p/5081971.html
Copyright © 2011-2022 走看看