当前位置: 代码迷 >> 综合 >> day18(Map集合 HashMap LinkedHashMap TreeMap 模拟洗牌和发牌)笔记
  详细解决方案

day18(Map集合 HashMap LinkedHashMap TreeMap 模拟洗牌和发牌)笔记

热度:31   发布时间:2023-12-18 18:08:35.0

18.01_集合框架(Map集合概述和特点)

  • A:Map<K,V>接口概述

    • 查看API可以知道:
      • 将键映射到值的对象
      • 一个映射不能包含重复的键
      • 每个键最多只能映射到一个值
  • B:Map接口和Collection接口的不同

    • Map是双列的,Collection是单列的
    • Map(HashMap,TreeMap)的键唯一,Collection的子体系Set(HashSet,TreeSet)是唯一的Set底层依赖Map,单列依赖双列
    • Map集合的数据结构值针对键有效,跟值无关;Collection集合的数据结构是针对元素有效

18.02_集合框架(Map集合的功能概述)

  • A:Map集合的功能概述
    • a:添加功能

      • V put(K key,V value):添加元素,两个引用数据类型
        • 如果键是第一次存储,就直接存储元素,返回null
        • 如果键不是第一次存在,相同的键不存储,值覆盖,把被覆盖的值返回
    • b:删除功能

      • void clear():移除所有的键值对元素
      • V remove(Object key):根据键删除键值对应元素,并把值返回
    • c:判断功能

      • boolean containsKey(Object key):判断集合是否包含指定的键
      • boolean containsValue(Object value):判断集合是否包含指定的值
      • boolean isEmpty():判断集合是否为空
    • d:获取功能

      • Set<Map.Entry<K,V>> entrySet():拿到所有的键值对象
      • V get(Object key):根据键获取值
      • Set keySet():获取集合中所有键的集合
      • Collection values():获取集合中所有值的集合,返回类型:Collection
    • e:长度功能

      • int size():返回集合中的键值对的个数

18.03_集合框架(Map集合的遍历之 键找值)

  • A:键找值思路:(通过查看Map集合的api发现没有iterator方法,那么双列集合如何迭代呢?)
    • 获取所有键的集合
    • 遍历键的集合,获取到每一个键
    • 根据键找值
  • B:案例演示
    • Map集合的遍历之键找值

        HashMap<String, Integer> hm = new HashMap<>();		//有序排列hm.put("张三", 23);hm.put("李四", 24);hm.put("王五", 25);hm.put("赵六", 26);//获取所有的键/*Set<String> keySet = hm.keySet();			//获取集合中所有的键,Set集合里有IteratorIterator<String> it = keySet.iterator();	//获取迭代器while(it.hasNext()) {						//判断单列集合中是否有元素String key = it.next();					//获取集合中的每一个元素,其实就是双列集合中的键Integer value = hm.get(key);			//根据键获取值System.out.println(key + "=" + value);	//打印键值对}*/for(String key : hm.keySet()) {				//增强for循环迭代双列集合第一种方式System.out.println(key + "=" + hm.get(key));}
      

18.04_集合框架(Map集合的遍历之 键值对对象找键和值)

  • A:键值对对象找键和值思路:

    • 获取所有键值对对象的集合
    • 遍历键值对对象的集合,获取到每一个键值对对象
    • 根据键值对对象找键和值
  • B:案例演示

    • Map集合的遍历之键值对对象找键和值

        HashMap<String, Integer> hm = new HashMap<>();hm.put("张三", 23);hm.put("李四", 24);hm.put("王五", 25);hm.put("赵六", 26);//Map.Entry说明Entry是Map的内部接口,将键和值封装成了Entry对象,并存储在Set集合中/*Set<Map.Entry<String, Integer>> entrySet = hm.entrySet();	//获取所有的键值对象的集合,Entry接口是Map接口的内部接口Iterator<Entry<String, Integer>> it = entrySet.iterator();//获取迭代器while(it.hasNext()) {//获取每一个Entry对象//Map.Entry<String, Integer> en = it.next();	//父类引用指向子类对象Entry<String, Integer> en = it.next();	//直接获取的是子类对象,Entry是Map.Entry的子类对象String key = en.getKey();								//根据键值对对象获取键Integer value = en.getValue();							//根据键值对对象获取值System.out.println(key + "=" + value);}*/for(Entry<String,Integer> en : hm.entrySet()) {System.out.println(en.getKey() + "=" + en.getValue());}
      
  • C:源码分析
    Map.Entry<String, Integer> en = it.next(); //父类引用指向子类对象
    Entry<String, Integer> en = it.next(); //直接获取的是子类对象,Entry是Map.Entry的子类对象,不需要写成Map.Entry<String, Integer>

18.05_集合框架(HashMap集合键是Student值是String的案例)

  • A:案例演示
    • HashMap集合键是Student,值是String的案例

        /** 键是学生对象,代表每一个学生* 值是字符串对象,代表学生归属地*/public static void main(String[] args) {HashMap<Student, String> hm = new HashMap<>();hm.put(new Student("张三", 23), "北京");hm.put(new Student("张三", 23), "上海");System.out.println(hm);}
      

18.06_集合框架(LinkedHashMap的概述和使用)

  • A:案例演示
    • LinkedHashMap的特点
      • 底层是链表实现的可以保证怎么存就怎么取

          public static void main(String[] args) {LinkedHashMap<String, Integer> lhm = new LinkedHashMap<>();lhm.put("张三", 23);lhm.put("李四", 24);lhm.put("赵六", 26);	System.out.println(lhm);}
        

18.07_集合框架(TreeMap集合键是Student值是String的案例)

  • A:案例演示
    • TreeMap集合键是Student,值是String的案例

        public static void main(String[] args) {//demo1();TreeMap<Student, String> tm = new TreeMap<>(new Comparator<Student>() {@Override	//比较Student,重写Comparator方法,比较键值public int compare(Student s1, Student s2) {int num = s1.getName().compareTo(s2.getName());		//按照姓名比较return num == 0 ? s1.getAge() - s2.getAge() : num;}});	//匿名内部类,传比较器Comparatortm.put(new Student("张三", 23), "北京");tm.put(new Student("李四", 13), "上海");tm.put(new Student("赵六", 43), "深圳");tm.put(new Student("王五", 33), "广州");System.out.println(tm);}public static void demo1() {TreeMap<Student, String> tm = new TreeMap<>();tm.put(new Student("张三", 23), "北京");tm.put(new Student("李四", 13), "上海");tm.put(new Student("王五", 33), "广州");tm.put(new Student("赵六", 43), "深圳");System.out.println(tm);	//类型转换异常,Student类中要实现Comparable<Student>接口,重写compareTo方法;HashMap需要重写HashCode和equals方法,此处是TreeMap,要重写compareTo方法}
      

18.08_集合框架(统计字符串中每个字符出现的次数)

  • A:案例演示
    • 需求:统计字符串中每个字符出现的次数
    •   String str = "aaaabbbcccccccccc";char[] arr = str.toCharArray();						//将字符串转换成字符数组HashMap<Character, Integer> hm = new HashMap<>();	//创建双列集合存储键和值,一般用HashMap,HashMap效率最高,TreeMap要排序,LinkedHashMap链表实现,怎么存怎么取for(char c : arr) {		//遍历字符数组/*if(!hm.containsKey(c)) {		//如果不包含这个键hm.put(c, 1);		//就将键和值为1添加}else {			//如果包含这个键hm.put(c, hm.get(c) + 1);		//就将键和值再加1添加进来}*/hm.put(c, !hm.containsKey(c) ? 1 : hm.get(c) + 1);/*Integer i = !hm.containsKey(c) ? hm.put(c, 1) : hm.put(c, hm.get(c) + 1);*/}for (Character key : hm.keySet()) {			//Character(包装器类型)可以写成char(基本数据类型),因为会自动装箱;遍历双列集合;//hm.keySet()代表所有键的集合System.out.println(key + "=" + hm.get(key));	//hm.get(key)根据键获取值}
      

18.09_集合框架(集合嵌套之HashMap嵌套HashMap)

  • A:案例演示
    • 集合嵌套之HashMap嵌套HashMap(之前有ArrayList嵌套ArrayList)

        /*** * A:案例演示* 集合嵌套之HashMap嵌套HashMap* * 需求:* 双元课堂有很多基础班* 第88期基础班定义成一个双列集合,键是学生对象,值是学生的归属地* 第99期基础班定义成一个双列集合,键是学生对象,值是学生的归属地* * 无论88期还是99期都是班级对象,所以为了便于统一管理,把这些班级对象添加到双元课堂集合中*/public static void main(String[] args) {//定义88期基础班HashMap<Student, String> hm88 = new HashMap<>();hm88.put(new Student("张三", 23), "北京");hm88.put(new Student("李四", 24), "北京");//定义99期基础班HashMap<Student, String> hm99 = new HashMap<>();hm99.put(new Student("唐僧", 1023), "北京");hm99.put(new Student("孙悟空",1024), "北京");//定义双元课堂,把整个集合对象看做一个键HashMap<HashMap<Student, String>, String> hm = new HashMap<>();hm.put(hm88, "第88期基础班");hm.put(hm99, "第99期基础班");//遍历双列集合for(HashMap<Student, String> h : hm.keySet()) {		//hm.keySet()代表的是双列集合中键的集合,即hm88和hm99String value = hm.get(h);		//get(h)根据键对象获取值对象//遍历 键的 双列集合对象for(Student key : h.keySet()) {		//h.keySet()获取集合总所有的学生键对象String value2 = h.get(key);		//获取键对应的值,即hm88对应的值,hm99对应的值System.out.println(key + "=" + value2 + "=" + value);	//一个输出:Student[name=孙悟空,age=1024]=北京=第99期基础班;key对应姓名年龄,即内层双列集合的键,value2对应归属地,即内层双列集合的值,value代表第多少期,即外层双列集合的值}}}
      

18.10_集合框架(HashMap和Hashtable的区别)

  • A:面试题
    • HashMap和Hashtable的共同点
      • 底层都是哈希算法,都是双列集合
    • HashMap和Hashtable的区别
      • Hashtable是JDK1.0版本出现的,是线程安全的,效率低,HashMap是JDK1.2版本出现的,是线程不安全的,效率高
      • Hashtable不可以存储null键和null值,HashMap可以存储null键和null值
  • B:案例演示
    • HashMap和Hashtable的区别

        public static void main(String[] args) {HashMap<String, Integer> hm = new HashMap<>();hm.put(null, 23);hm.put("李四", null);System.out.println(hm);/*Hashtable<String, Integer> ht = new Hashtable<>();ht.put(null, 23);ht.put("张三", null);System.out.println(ht);	//运行报错*/}
      

18.11_集合框架(Collections工具类的概述和常见方法讲解)

  • A:Collections类概述
    • 针对集合操作的工具类,类中方法都是静态的,不能重写,只能直接调用
  • B:Collections的常见成员方法
  •   /*public static <T> void sort(List<T> list)	//只提供给List集合,因为TreeSet可以排序public static <T> int binarySearch(List<?> list,T key)	//二分查找法,如果搜索键包含在列表中,则返回搜索键的索引;否则返回(-(插入点)-1)。public static <T> T max(Collection<?> coll)	//根据默认排序结果获取集合中的最大值public static void reverse(List<?> list)	//反转集合public static void shuffle(List<?> list)	//随机置换,可以用来洗牌*/public static void main(String[] args) {//demo1();//demo2();ArrayList<String> list = new ArrayList<>();list.add("a");list.add("c");list.add("d");list.add("g");list.add("f");//System.out.println(Collections.max(list)); 	//根据默认排序结果获取集合中的最大值,compareTo排序Collections.reverse(list);		//反转集合Collections.shuffle(list);		//随机置换,可以用来洗牌System.out.println(list);}public static void demo2() {ArrayList<String> list = new ArrayList<>();list.add("a");list.add("c");list.add("d");list.add("f");list.add("g");System.out.println(Collections.binarySearch(list, "c"));	//1System.out.println(Collections.binarySearch(list, "b"));	//-2,(-(1)-1)}public static void demo1() {ArrayList<String> list = new ArrayList<>();list.add("c");list.add("a");list.add("a");list.add("b");list.add("d");Collections.sort(list);		//具有比较性,类实现了Comparable,就可以将集合排序,此处按String排序System.out.println(list);	//[a,a,b,c,d],TreeSet也可以}
    

18.12_集合框架(模拟斗地主洗牌和发牌)

  • A:案例演示
    • 模拟斗地主洗牌和发牌,牌没有排序

        //买一副扑克String[] num = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};String[] color = {"方片","梅花","红桃","黑桃"};ArrayList<String> poker = new ArrayList<>();//拼接花色和数字for(String s1 : color) {for(String s2 : num) {poker.add(s1.concat(s2));	//concat连接两个字符串}}poker.add("小王");poker.add("大王");//洗牌Collections.shuffle(poker);//发牌ArrayList<String> gaojin = new ArrayList<>();ArrayList<String> longwu = new ArrayList<>();ArrayList<String> me = new ArrayList<>();ArrayList<String> dipai = new ArrayList<>();for(int i = 0; i < poker.size(); i++) {if(i >= poker.size() - 3) {dipai.add(poker.get(i));	//将三张底牌存储在底牌集合中}else if(i % 3 == 0) {gaojin.add(poker.get(i));	//第一张牌发给gaojin,0,3,6,9,,,}else if(i % 3 == 1) {longwu.add(poker.get(i));	//第二张牌发给longwu,1,4,7,10,,,}else {me.add(poker.get(i));	//第三张牌发给me,2,5,8,,,}}//看牌			System.out.println(gaojin);System.out.println(longwu);System.out.println(me);System.out.println(dipai);
      

18.13_集合框架(模拟斗地主洗牌和发牌并对牌进行排序的原理图解)

  • A:画图演示
    • 画图说明排序原理
      • HashMap<Integer,String>
      • 将键值作为ArrayList集合,ArrayList作为洗牌洗的索引,然后根据索引获取值,值就相当于被洗乱了
      • 然后将每个人的牌放入TreeSet中排序

18.14_集合框架(模拟斗地主洗牌和发牌并对牌进行排序的代码实现)

  • A:案例演示
    • 模拟斗地主洗牌和发牌并对牌进行排序的代码实现
  •   	//买一副牌String[] num = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};String[] color = {"方片","梅花","红桃","黑桃"};HashMap<Integer, String> hm = new HashMap<>();		//存储索引和扑克牌ArrayList<Integer> list = new ArrayList<>();	//存储索引int index = 0;	//索引的开始值//拼接扑克牌并索引和扑克牌存储在hm中for(String s1 : num) {		//获取数字for(String s2 : color) {	hm.put(index, s2.concat(s1));		//将索引和扑克牌添加到HashMap中list.add(index);	//将索引添加到ArrayList集合中index++;	}}hm.put(index, "小王");		//将小王添加到双列集合中list.add(index);		//将52索引添加到集合中index++;hm.put(index, "大王");list.add(index);		//将53索引添加到集合中//洗牌Collections.shuffle(list);//发牌TreeSet<Integer> gaojin = new TreeSet<>();TreeSet<Integer> longwu = new TreeSet<>();TreeSet<Integer> me = new TreeSet<>();TreeSet<Integer> dipai = new TreeSet<>();for(int i = 0; i < list.size(); i++) {if(i >= list.size() - 3) {dipai.add(list.get(i)); 		//将list集合中的索引添加到TreeSet集合中会自动排序,将三张底牌存储在底牌集合中}else if(i % 3 == 0) {gaojin.add(list.get(i));}else if(i % 3 == 1) {longwu.add(list.get(i));}else {me.add(list.get(i));}}	//拿到现在的都是索引//看牌lookPoker("高进", gaojin, hm);lookPoker("龙五", longwu, hm);lookPoker("冯佳", me, hm);lookPoker("底牌", dipai, hm);}public static void lookPoker(String name,TreeSet<Integer> ts,HashMap<Integer, String> hm) {System.out.print(name + "的牌是:");for (Integer i : ts) {		//i代表双列集合中的每一个键,ts是单列的System.out.print(hm.get(i) + " ");}System.out.println();	//每人排一行}
    

18.15_集合框架(泛型固定下边界)

  • ? super E

      	public class Demo2_Genric {/*** 泛型固定下边界* ? super E  * * 泛型固定上边界* ? extends E*/public static void main(String[] args) {//demo1();TreeSet<Student> ts1 = new TreeSet<>(new CompareByAge());ts1.add(new Student("张三", 33));ts1.add(new Student("李四", 13));ts1.add(new Student("王五", 23));ts1.add(new Student("赵六", 43));//BaseStudent是Student的子类TreeSet<BaseStudent> ts2 = new TreeSet<>(new CompareByAge());ts2.add(new BaseStudent("张三", 33));ts2.add(new BaseStudent("李四", 13));ts2.add(new BaseStudent("王五", 23));ts2.add(new BaseStudent("赵六", 43));System.out.println(ts2);// 实现Comparator<Student>泛型接口,泛型是Student,但子类BaseStudent仍能调用,也算父类引用指向子类对象,泛型固定下边界: ? super E  }public static void demo1() {ArrayList<Student> list1 = new ArrayList<>();list1.add(new Student("张三", 23));list1.add(new Student("李四", 24));//BaseStudent是Student的子类ArrayList<BaseStudent> list2 = new ArrayList<>();list2.add(new BaseStudent("王五", 25));list2.add(new BaseStudent("赵六", 26));list1.addAll(list2);	//父类引用指向子类对象,把子类对象添加到父类的集合里去,即 泛型固定上边界: ?(子类) extends E(父类)}}class CompareByAge implements Comparator<Student> {@Overridepublic int compare(Student s1, Student s2) {int num = s1.getAge() - s2.getAge();return num == 0 ? s1.getName().compareTo(s2.getName()) :  num;}
    

18.16_day 18总结

  • 把今天的知识点总结一遍。

      /*** Collection* 		List(存取有序,有索引,可以重复)* 			ArrayList* 				底层是数组实现的,线程不安全,查找和修改快,增和删比较慢* 			LinkedList* 				底层是链表实现的,线程不安全,增和删比较快,查找和修改比较慢* 			Vector* 				底层是数组实现的,线程安全的,无论增删改查都慢* 			如果查找和修改多,用ArrayList* 			如果增和删多,用LinkedList* 			如果都多,用ArrayList* 		Set(存取无序,无索引,不可以重复)* 			HashSet* 				底层是哈希算法实现* 				LinkedHashSet* 					底层是链表实现,但是也是可以保证元素唯一,和HashSet原理一样* 			TreeSet* 				底层是二叉树算法实现* 			一般在开发的时候不需要对存储的元素排序,所以在开发的时候大多用HashSet,HashSet的效率比较高* 			TreeSet在面试的时候比较多,问你有几种排序方式,和几种排序方式的区别* Map* 		HashMap* 			底层是哈希算法,针对键* 			LinkedHashMap* 				底层是链表,针对键* 		TreeMap* 			底层是二叉树算法,针对键* 		开发中用HashMap比较多* 		单列集合,有重复元素,优先ArrayList,不需要重复元素,优先HashSet;* 		双列元素,优先HashMap,要排序,选TreeSet*/
    
  相关解决方案