可变参数 - Collections - Map

180 阅读4分钟

可变参数 - Collections - Map

1 可变参数

1.1 概念

​ 是一种特殊参数格式

1.2 格式

​ 数据类型... 参数名称;

1.3 特点

​ 1) 可以不传数据给它

​ 2) 可以传一个或者同时传多个数据给它

​ 3) 也可以传一个数组给它

1.4 好处

​ 常常用来灵活的接收数据

1.5 注意事项

​ 1) 可变参数在方法内部就是一个数组

​ 2) 一个形参列表中可变参数只能有一个

​ 3) 可变参数必须放在形参列表的最后面

public static int findMax(int...i){
       //...省略方法内容
}

2 Collections

2.1 作用

​ 是一个用来操作集合的工具类

2.2 常用方法

​ - 给集合批量添加元素: public static boolean addAll(Collection<? super T> c, T... elements)

​ - 打乱List集合中的元素顺序: public static void shuffle(List<?> list)

​ - 对List集合中的元素进行升序排序: public static void sort(List list)

​ - 对List集合中元素,按照比较器对象指定的规则进行排序: public static void sort(List list,Comparator<? super T> c)

3 Map

3.1 概念

​ Map集合称为双列集合, 是一个键值对映射的集合。每个键只能对应一个值,但是不同的键可以对应相同的值。(字典?)

3.2 注意事项

​ Map集合的所有键是不允许重复的,但值可以重复,键和值是一一对应的,每一个键只能找到自己对应的值

3.3 Map的体系
3.3.1 HashMap

​ (由键决定特点): 无序、不重复、无索引; (用的最多)

​ 其底层原理是用基于哈希表实现

3.3.2 LinkedHashMap

​ (由键决定特点):由键决定的特点:有序、不重复、无索引

​ 底层数据结构依然是基于哈希表实现的,只是每个键值对元素又额外的多了一个双链表的机制记录元素顺序(保证有序)

3.3.3TreeMap

​ (由键决定特点):按照大小默认升序排序、不重复、无索引

​ TreeMap底层原理跟TreeSet集合的底层原理是一样的,都是基于红黑树实现的排序

​ 排序规则:

​ 1) 让类实现Comparable接口,重写比较规则.

​ 2) TreeMap集合有一个有参数构造器,支持创建Comparator比较器对象,以便用来指定比较规则

3.4 Map的常用方法

​ - 添加元素: public V put(K key,V value)

​ - 获取集合的大小: public int size()

​ - 清空集合: public void clear()

​ - 判断集合是否为空,为空返回true , 反之返回false: public boolean isEmpty()

​ - 根据键获取对应值: public V get(Object key)

​ - 根据键删除整个元素: public V remove(Object key)

​ - 判断是否包含某个键: public boolean containsKey(Object key)

​ - 判断是否包含某个值: public boolean containsValue(Object value)

​ - 获取全部键的集合: public Set keySet()

​ - 获取Map集合的全部值: public Collection values()

3.5 遍历方式
3.5.1 先获取Map集合全部的键,再通过遍历键来找值

​ 1) 获取所有键的集合: public Set keySet()

​ 2) 根据键获取其对应的值: public V get(Object key)

public static void main(String[] args) {
    Map<String, Integer> map = new HashMap<>();
    map.put("Yui",66);
    map.put("Yukirin",60);
    map.put("Zukky",17);
    map.put("Hi-chan",37);
    System.out.println(map);
    //下列三种方法重复使用
//     getkey value
    Set<String> strings = map.keySet();
//     for loop get key's value
    for (String string : strings) {
        Integer vStr = map.get(string);
        System.out.println(string+"====>"+vStr);
    }
3.5.2 把“键值对“看成一个整体进行遍历(难度较大)

​ 1) 获取所有“键值对”的集合: Set<Map.Entry<K, V>> entrySet()

​ 2) 获取键: K getKey()

​ 3) 获取值: V getValue()

// entry就是键值对, 此处获取了一个Entry(接口)的子类对象entries同时包含泛型<String, Integer>的set
Set<Map.Entry<String, Integer>> entries = map.entrySet();
// 对上文get的set进行遍历
for (Map.Entry<String, Integer> entry : entries) {
    String str = entry.getKey();
    Integer integer = entry.getValue();
    System.out.println(str+"====>"+integer);
3.5.3 用forEach(简单)

​ 1) forEach

​ 2) New BiConsumer 并重写

map.forEach(new BiConsumer<String, Integer>() {
    @Override
    public void accept(String s, Integer integer) {
        System.out.println(s+"=====>"+integer);
    }
});

4 集合嵌套

​ 集合如果发生嵌套, 遍历的时候可以经过多次遍历, 一一读取元素.

import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

public class test {
    public static void main(String[] args) {
        HashSet<String> cities1 = new HashSet<>();
        HashSet<String> cities2 = new HashSet<>();
        HashSet<String> cities3 = new HashSet<>();
        Collections.addAll(cities1, "南京市", "扬州市", "苏州市", "无锡市", "常州市");
        Collections.addAll(cities2, "武汉市", "孝感市", "十堰市", "宜昌市", "鄂州市");
        Collections.addAll(cities3, "石家庄市", "唐山市", "邢台市", "保定市", "张家口市");

        // System.out.println(cities1);
        Map<String, HashSet> map = new HashMap<>();
        map.put("江苏省", cities1);
        map.put("湖北省", cities2);
        map.put("河北省", cities3);

        // System.out.println(map);

        HashSet outCity = map.get("湖北省");
        System.out.println(outCity);

    //     遍历嵌套数组
        map.forEach(new BiConsumer<String, HashSet>() {
            @Override
            public void accept(String s, HashSet hashSet) {
                System.out.print("\n省份为"+s+"的市有: ");
                hashSet.forEach(new Consumer() {
                    @Override
                    public void accept(Object o) {
                        System.out.print(o+"\t");
                    }
                });
            }
        });

    }
}

5 斗地主扑克牌案例

package 扑克牌小案例.re;

import java.util.ArrayList;
import java.util.Collections;

public class Poker {
    private String points;
    private String colors;
    private int count;

    //创建cardSet方法,该方法可以导出一副牌集合
    public static ArrayList cardSet(){
        // 牌的花色和点数按String array存入
        String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
        String[] colors = {"♦", "♣", "♥", "♠"};
        // 创建新的Arraylist
        ArrayList arrayList = new ArrayList<>();
        // initialization
        int i = 0;
        // 遍历 获取所有花色点数
        for (String number : numbers) {
            for (String color : colors) {
                // 创建新的对象, 即抛性
                Poker poker = new Poker(number, color, i++);
                //将新的对象poker放入arraylist
                arrayList.add(poker);
            }
        }
        // 放入大小王
        Poker xw = new Poker("","大王",i++);
        Poker dw = new Poker("","小王",i++);

        Collections.addAll(arrayList,xw,dw);
        return arrayList;
    }

    public Poker() {
    }

    public Poker(String points, String colors, int count) {
        this.points = points;
        this.colors = colors;
        this.count = count;
    }

    /**
     * 获取
     * @return points
     */
    public String getPoints() {
        return points;
    }

    /**
     * 设置
     * @param points
     */
    public void setPoints(String points) {
        this.points = points;
    }

    /**
     * 获取
     * @return colors
     */
    public String getColors() {
        return colors;
    }

    /**
     * 设置
     * @param colors
     */
    public void setColors(String colors) {
        this.colors = colors;
    }

    /**
     * 获取
     * @return count
     */
    public int getCount() {
        return count;
    }

    /**
     * 设置
     * @param count
     */
    public void setCount(int count) {
        this.count = count;
    }

    public String toString() {
        return points + "" + colors;
    }
}
package 扑克牌小案例.re;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
import java.util.function.Consumer;

public class gameStart {
    public static void main(String[] args) {
        ArrayList<Poker> arrayList = Poker.cardSet();
        Scanner sc = new Scanner(System.in);
        // System.out.println(arrayList);

        //     分给三个人
        ArrayList<Poker> player1 = new ArrayList<>();
        ArrayList<Poker> player2 = new ArrayList<>();
        ArrayList<Poker> player3 = new ArrayList<>();
        // 底牌
        ArrayList<Poker> hide = new ArrayList();


        //     抽取前先打乱顺序
        Collections.shuffle(arrayList);
        //     已知需要抽取51张
        for (int i = 0; i < 51; i++) {
            if (i % 3 == 0) {
                player1.add(arrayList.get(i));
            } else if (i % 3 == 1) {
                player2.add(arrayList.get(i));
            } else {
                player3.add(arrayList.get(i));
            }
        }
        hide.add(arrayList.get(51));
        hide.add(arrayList.get(52));
        hide.add(arrayList.get(53));


        System.out.println("玩家一的牌: " + player1);
        System.out.println("玩家二的牌: " + player2);
        System.out.println("玩家三的牌: " + player3);
        System.out.println("底牌: " + hide);
        System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
        System.out.println("玩家几号叫地主? ");
        int i = sc.nextInt();
        switch (i) {
            case 1:
                for (Poker poker : hide) {
                    player1.add(poker);
                }
                System.out.println("底牌已经交给1号玩家");
                break;
            case 2:
                for (Poker poker : hide) {
                    player2.add(poker);
                }
                System.out.println("底牌已经交给3号玩家");
                break;
            case 3:
                for (Poker poker : hide) {
                    player3.add(poker);
                }
                System.out.println("底牌已经交给3号玩家");
                break;

        }
        // 排序
        Collections.sort(player1, new Comparator<Poker>() {
            @Override
            public int compare(Poker o1, Poker o2) {
                return o1.getCount() - o2.getCount();
            }
        });
        Collections.sort(player2, new Comparator<Poker>() {
            @Override
            public int compare(Poker o1, Poker o2) {
                return o1.getCount() - o2.getCount();
            }
        });
        Collections.sort(player3, (o1, o2) -> {
            return o1.getCount() - o2.getCount();
        });
        System.out.println("玩家一的牌: " + player1);
        System.out.println("玩家二的牌: " + player2);
        System.out.println("玩家三的牌: " + player3);
        System.out.println("底牌: " + hide);
    }
}