java shuffle an ordered array

1. Add a sequential array to the collection


2. You can use the shuffle() method of the collection helper class Collections


3. Traverse the input collection with hasNext() and next() methods


/** 
 * Then shuffle an array 
 */  
import java.util.ArrayList;  
import java.util.Collections;  
import java.util.Iterator;  
import java.util.List;  
  
  
public class Shuffle {  
      

    public static void main(String[] args) { 

        shuffle(); ------- call this method
    }  
      //define this static method

    public static void shuffle(){  

       int[] x = {1,2,3,4,5,6}; --------Define an ordered array of int type and initialize
        List list = new ArrayList(); ---- ----Create a list collection to store the array
        for(int i = 0;i < x.length;i++){ -------traverse the array
            System.out.print(x[i]+", ");  
            list.add(x[i]); ------- add array elements to the collection storage
        }  
        System.out.println();  
          
        Collections.shuffle(list); ------ Call  Collections.shuffle(); method to shuffle the array order
          
        Iterator ite = list.iterator(); -------Use iterator to traverse the collection
        while(ite.hasNext()){  
            System.out.print(ite. next().toString()+", "); ------ output collection
        }  
    }  
}  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324753779&siteId=291194637