Java集合List模拟“洗牌”操作

Collection工具类为操作List集合提供了几个有用的方法:

            reverse()、shuffle()、sort()、swap()、rotate()。

小例子: 使用shuffle(),方法模拟洗牌操作,并输出。

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;



public class ShuffleCards {
   private String[] types = {"方块","草花","黑桃","红心"};
   private String[] values = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
   private List<String> cards = new LinkedList<String>();
   //private int length;
   public void initCards(){
       for(int i=0;i<types.length;i++){
           for(int j=0;j<values.length;j++){
               cards.add(types[i]+values[j]);
           }
       }
       
       Collections.shuffle(cards);
       ListIterator lit = cards.listIterator();
       while(lit.hasNext()){
           System.out.println(lit.next());
       } 
   }

   
   public static void main(String[] args){
       ShuffleCards sc = new ShuffleCards();
       sc.initCards();
      
      
   }
}
原文地址:https://www.cnblogs.com/skylar/p/3660534.html