Collections中的shuffle()方法


shuffle() 是 Collections 中的靜態方法 ,它用於將一個 list 集合中的元素順序進行打亂 ,類似於洗牌的過程,而且shuffle的

英文含義就是 “洗牌” 。shuffle()方法常用於類似 洗牌要打亂順序 的問題。

eg: 模擬洗牌

import java.util.*;

public class Card {
      public static enum Face {
           紅心 , 方塊 , 草花 , 黑桃
     };

      public static enum Deck {
           one , two , three , four , five , six , seven , eight , nine , ten , eleven , tweleve , thirteen
     };

      /**
      *
      * 私有變量將從枚舉Face, Deck中獲得值,那么其返回值應該定義成枚舉( enum)嗎? 是的,但是需要使用Face face, Deck
      * deck;
      *
      */
      private Face face ;
      private Deck deck ;

      public Card(Face faceVal, Deck deckVal) {
           face = faceVal;
           deck = deckVal;
     }

      public String toString() {
           // return String.format("%s of %s", deck, face);
           return String. format( face + " " + deck );
     }

      public static void main(String argc[]) {
          Card card[] = new Card[52];
           int counter = 0;

           for (Card.Face faceVal : Card.Face. values()) {
               for (Card.Deck deckVal : Card.Deck.values()) {
                   card[counter++] = new Card(faceVal, deckVal);
              }
          }

          List<Card> list = Arrays. asList(card); // 將數組轉化成collection

          Collections. shuffle(list); // 利用集合(collections)的靜態方法,打亂list集合順序
          Card[] card2 = new Card[52]; // 創建新數組
          list.toArray(card2); // 將collection轉換成數組,以便輸出

           for (Card c : card2) {
              System. out .println(c + " " );
          }
     }
}
輸出結果:
黑桃 two
草花 ten
草花 nine
草花 seven
黑桃 eight
方塊 one
黑桃 tweleve
黑桃 thirteen
草花 one
黑桃 nine
黑桃 six
草花 six
黑桃 four
草花 eight
紅心 nine
紅心 one
草花 four
紅心 five
紅心 tweleve
黑桃 eleven
黑桃 three
方塊 ten
方塊 five
方塊 four
紅心 eight
紅心 four
草花 thirteen
紅心 thirteen
方塊 two
方塊 six
草花 eleven
紅心 six
草花 three
紅心 two
黑桃 one
方塊 nine
紅心 eleven
紅心 ten
紅心 three
方塊 tweleve
草花 five
方塊 eleven
黑桃 five
黑桃 seven
方塊 eight
黑桃 ten
草花 two
方塊 seven
草花 tweleve
紅心 seven
方塊 three
方塊 thirteen 





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM