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]; // 创建新数组
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
发布评论