天天看點

Java學習-工具IDEA-黑馬視訊(第十四天)

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();
    }