Collections类
-
- Collections的几个静态方法
- 升级版斗地主
Collections的几个静态方法
List<Integer> list = new ArrayList<>();
list.add(20);
list.add(30);
list.add(50);
list.add(40);
list.add(60);
//public static <T extends Comparable<? super T>> void sort(List<T> list),将指定的列表升序排列
// Collections.sort(list);
//还可以传一个比较器在里面
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
int temp = 0;
if (o1 > o2) {
temp = -1;
} else if (o1 < o2) {
temp = 1;
}
return temp;
}
});
// //数组排序反转
// Collections.reverse(list);
//
// //随机置换
// Collections.shuffle(list);
System.out.println(list);
升级版斗地主
public static void main(String[] args) {
HashMap<Integer, String> hm = new HashMap<>();
ArrayList<Integer> array = new ArrayList<>();
String[] colors = {"♦", "♠", "♥", "♣"};
String[] numbers = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
int index = 0;
for (String number : numbers) {
for (String color : colors) {
hm.put(index, color + number);
array.add(index);
index++;
}
}
hm.put(index, "小王");
array.add(index);
hm.put(++index, "大王");
array.add(index);
Collections.shuffle(array);
TreeSet<Integer> JYQ = new TreeSet<>();
TreeSet<Integer> WST = new TreeSet<>();
TreeSet<Integer> WYX = new TreeSet<>();
TreeSet<Integer> DiPai = new TreeSet<>();
for (int i = 0; i < array.size(); i++) {
int pokerIndex = array.get(i);
if (i >= array.size() - 3) {
DiPai.add(pokerIndex);
} else if (i % 3 == 0) {
JYQ.add(pokerIndex);
} else if (i % 3 == 1) {
WST.add(pokerIndex);
} else if (i % 3 == 2) {
WYX.add(pokerIndex);
}
}
lookPoker("JYQ",JYQ,hm);
lookPoker("WST",WST,hm);
lookPoker("WYX",WYX,hm);
lookPoker("底牌",DiPai,hm);
}
public static void lookPoker (String name, TreeSet < Integer > array, HashMap < Integer, String > hm){
System.out.println(name + "的牌是:");
for(Integer key : array){
String poker = hm.get(key);
System.out.print(poker+" ");
}
System.out.println();
}