Java集合篇

2023-05-16

文章目录

    • 1. Collection集合
      • 1.1 集合体系结构
      • 1.2 Collection集合概述和基本使用
      • 1.3 Collection集合的常用方法
      • 1.4 Collection集合的遍历
      • 1.5 集合使用步骤图解
      • 1.6 集合的案例-Collection集合存储学生对象并遍历
    • 2. List集合
      • 2.1 List集合概述和特点
      • 2.2 List集合的特有方法
      • 2.3 集合的案例-List集合存储学生对象并遍历
      • 2.4 并发修改异常
      • 2.5 列表迭代器
      • 2.6 增强for循环
      • 2.7 集合的案例-List集合存储学生对象三种方式遍历
    • 3. 数据结构
      • 3.1 数据结构之栈和队列
      • 3.2 数据结构之数组和链表
    • 4. List集合的实现类
      • 4.1 List集合子类的特点
      • 4.2 集合的案例-ArrayList集合存储学生对象三种方式遍历
      • 4.3 LinkedList集合的特有功能
    • 5. Set集合
      • 5.1 Set集合概述和特点
      • 5.2 哈希值
      • 5.3 HashSet集合概述和特点
      • 5.4 HashSet集合保证元素唯一性源码分析
      • 5.5 常见数据结构之哈希表
      • 5.6 HashSet集合存储学生对象并遍历
      • 5.7 LinkedHashSet集合概述和特点
    • 6. Set集合排序
      • 6.1 TreeSet集合概述和特点
      • 6.2 自然排序Comparable的使用
      • 6.3 比较器排序Comparator的使用
      • 6.4 成绩排序案例
      • 6.5 不重复的随机数案例
    • 7. 泛型
      • 7.1 泛型概述和好处
      • 7.2 泛型类
      • 7.3 泛型方法
      • 7.4 泛型接口
      • 7.5 类型通配符
    • 8. 可变参数
      • 8.1 可变参数
      • 8.2 可变参数的使用
    • 9. Map集合
      • 9.1 Map集合概述和特点
      • 9.2 Map集合的基本功能
      • 9.3 Map集合的获取功能
      • 9.4 Map集合的遍历(方式1)
      • 9.5 Map集合的遍历(方式2)
      • 9.6 Map集合的案例
        • 9.6.1 HashMap集合练习之键是String值是Student
        • 9.6.2 HashMap集合练习之键是Student值是String
        • 9.6.3 集合嵌套之ArrayList嵌套HashMap
        • 9.6.4 集合嵌套之HashMap嵌套ArrayList
        • 9.6.5 统计字符串中每个字符出现的次数
    • 10. Collections集合工具类
      • 10.1 Collections概述和使用
      • 10.2 ArrayList集合存储学生并排序
    • 11. 斗地主案例
      • 11.1 模拟斗地主案例-普通版本
      • 11.2 模拟斗地主案例-升级版本

1. Collection集合

1.1 集合体系结构

  • 集合类的特点

    ​ 提供一种存储空间可变的存储模型,存储的数据容量可以随时发生改变

  • 集合类的体系图

在这里插入图片描述

1.2 Collection集合概述和基本使用

  • Collection集合概述

    • 是单例集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素

    • JDK 不提供此接口的任何直接实现,它提供更具体的子接口(如Set和List)实现

  • Collection集合基本使用

    public class CollectionDemo01 {
        public static void main(String[] args) {
            //创建Collection集合的对象
            Collection<String> c = new ArrayList<String>();
    
            //添加元素:boolean add(E e)
            c.add("hello");
            c.add("world");
            c.add("java");
    
            //输出集合对象
            System.out.println(c);
        }
    }
    

1.3 Collection集合的常用方法

方法名说明
boolean add(E e)添加元素
boolean remove(Object o)从集合中移除指定的元素
void clear()清空集合中的元素
boolean contains(Object o)判断集合中是否存在指定的元素
boolean isEmpty()判断集合是否为空
int size()集合的长度,也就是集合中元素的个数

1.4 Collection集合的遍历

  • 迭代器的介绍
    • 迭代器,集合的专用遍历方式
    • Iterator iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
    • 迭代器是通过集合的iterator()方法得到的,所以我们说它是依赖于集合而存在的
  • Collection集合的遍历
public class IteratorDemo {
    public static void main(String[] args) {
        //创建集合对象
        Collection<String> c = new ArrayList<>();

        //添加元素
        c.add("hello");
        c.add("world");
        c.add("java");
        c.add("javaee");

        //Iterator<E> iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
        Iterator<String> it = c.iterator();

        //用while循环改进元素的判断和获取
        while (it.hasNext()) {
            String s = it.next();
            System.out.println(s);
        }
    }
}

1.5 集合使用步骤图解

  • 使用步骤

在这里插入图片描述

1.6 集合的案例-Collection集合存储学生对象并遍历

  • 案例需求

    ​ 创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合

  • 代码实现

    • 学生类
    public class Student {
        private String name;
        private int age;
    
        public Student() {
        }
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    }
    
    • 测试类
    public class CollectionDemo {
        public static void main(String[] args) {
            //创建Collection集合对象
            Collection<Student> c = new ArrayList<Student>();
    
            //创建学生对象
            Student s1 = new Student("林青霞", 30);
            Student s2 = new Student("张曼玉", 35);
            Student s3 = new Student("王祖贤", 33);
    
            //把学生添加到集合
            c.add(s1);
            c.add(s2);
            c.add(s3);
    
            //遍历集合(迭代器方式)
            Iterator<Student> it = c.iterator();
            while (it.hasNext()) {
                Student s = it.next();
                System.out.println(s.getName() + "," + s.getAge());
            }
        }
    }
    

2. List集合

2.1 List集合概述和特点

  • List集合概述
    • 有序集合(也称为序列),用户可以精确控制列表中每个元素的插入位置。用户可以通过整数索引访问元素,并搜索列表中的元素
    • 与Set集合不同,列表通常允许重复的元素
  • List集合特点
    • 有索引
    • 可以存储重复元素
    • 元素存取有序

2.2 List集合的特有方法

方法名描述
void add(int index,E element)在此集合中的指定位置插入指定的元素
E remove(int index)删除指定索引处的元素,返回被删除的元素
E set(int index,E element)修改指定索引处的元素,返回被修改的元素
E get(int index)返回指定索引处的元素

2.3 集合的案例-List集合存储学生对象并遍历

  • 案例需求

    ​ 创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合

  • 代码实现

    • 学生类

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      }
      
    • 测试类

      public class ListDemo {
          public static void main(String[] args) {
              //创建List集合对象
              List<Student> list = new ArrayList<Student>();
      
              //创建学生对象
              Student s1 = new Student("林青霞", 30);
              Student s2 = new Student("张曼玉", 35);
              Student s3 = new Student("王祖贤", 33);
      
              //把学生添加到集合
              list.add(s1);
              list.add(s2);
              list.add(s3);
      
              //迭代器方式
              Iterator<Student> it = list.iterator();
              while (it.hasNext()) {
                  Student s = it.next();
                  System.out.println(s.getName() + "," + s.getAge());
              }
              
              System.out.println("--------");
      
              //for循环方式
              for(int i=0; i<list.size(); i++) {
                  Student s = list.get(i);
                  System.out.println(s.getName() + "," + s.getAge());
              }
      
          }
      }
      

2.4 并发修改异常

  • 出现的原因

    ​ 迭代器遍历的过程中,通过集合对象修改了集合中的元素,造成了迭代器获取元素中判断预期修改值和实际修改值不一致,则会出现:ConcurrentModificationException

  • 解决的方案

    ​ 用for循环遍历,然后用集合对象做对应的操作即可

  • 示例代码

    public class ListDemo {
        public static void main(String[] args) {
            //创建集合对象
            List<String> list = new ArrayList<String>();
    
            //添加元素
            list.add("hello");
            list.add("world");
            list.add("java");
    
            //遍历集合,得到每一个元素,看有没有"world"这个元素,如果有,我就添加一个"javaee"元素,请写代码实现
    //        Iterator<String> it = list.iterator();
    //        while (it.hasNext()) {
    //            String s = it.next();
    //            if(s.equals("world")) {
    //                list.add("javaee");
    //            }
    //        }
    
            for(int i=0; i<list.size(); i++) {
                String s = list.get(i);
                if(s.equals("world")) {
                    list.add("javaee");
                }
            }
    
            //输出集合对象
            System.out.println(list);
        }
    }
    

2.5 列表迭代器

  • ListIterator介绍

    • 通过List集合的listIterator()方法得到,所以说它是List集合特有的迭代器
    • 用于允许程序员沿任一方向遍历的列表迭代器,在迭代期间修改列表,并获取列表中迭代器的当前位置
  • 示例代码

    public class ListIteratorDemo {
        public static void main(String[] args) {
            //创建集合对象
            List<String> list = new ArrayList<String>();
    
            //添加元素
            list.add("hello");
            list.add("world");
            list.add("java");
    
            //获取列表迭代器
            ListIterator<String> lit = list.listIterator();
            while (lit.hasNext()) {
                String s = lit.next();
                if(s.equals("world")) {
                    lit.add("javaee");
                }
            }
    
            System.out.println(list);
    
        }
    }
    

2.6 增强for循环

  • 定义格式

    for(元素数据类型 变量名 : 数组/集合对象名) {
    	循环体;
    }
    
  • 示例代码

      public class ForDemo {
          public static void main(String[] args) {
              int[] arr = {1,2,3,4,5};
              for(int i : arr) {
                  System.out.println(i);
              }
              System.out.println("--------");
      
              String[] strArray = {"hello","world","java"};
              for(String s : strArray) {
                  System.out.println(s);
              }
              System.out.println("--------");
      
              List<String> list = new ArrayList<String>();
              list.add("hello");
              list.add("world");
              list.add("java");
      
              for(String s : list) {
                  System.out.println(s);
              }
              System.out.println("--------");
      
              //内部原理是一个Iterator迭代器
              /*
              for(String s : list) {
                  if(s.equals("world")) {
                      list.add("javaee"); //ConcurrentModificationException
                  }
              }
              */
          }
      }
    

2.7 集合的案例-List集合存储学生对象三种方式遍历

  • 案例需求

    ​ 创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合

  • 代码实现

    • 学生类

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
      
      
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      }
      
      
    • 测试类

      public class ListDemo {
          public static void main(String[] args) {
              //创建List集合对象
              List<Student> list = new ArrayList<Student>();
      
              //创建学生对象
              Student s1 = new Student("林青霞", 30);
              Student s2 = new Student("张曼玉", 35);
              Student s3 = new Student("王祖贤", 33);
      
              //把学生添加到集合
              list.add(s1);
              list.add(s2);
              list.add(s3);
      
              //迭代器:集合特有的遍历方式
              Iterator<Student> it = list.iterator();
              while (it.hasNext()) {
                  Student s = it.next();
                  System.out.println(s.getName()+","+s.getAge());
              }
              System.out.println("--------");
      
              //普通for:带有索引的遍历方式
              for(int i=0; i<list.size(); i++) {
                  Student s = list.get(i);
                  System.out.println(s.getName()+","+s.getAge());
              }
              System.out.println("--------");
      
              //增强for:最方便的遍历方式
              for(Student s : list) {
                  System.out.println(s.getName()+","+s.getAge());
              }
          }
      }
      

3. 数据结构

3.1 数据结构之栈和队列

  • 栈结构

    ​ 先进后出

  • 队列结构

    ​ 先进先出

3.2 数据结构之数组和链表

  • 数组结构

    ​ 查询快、增删慢

  • 队列结构

    ​ 查询慢、增删快

4. List集合的实现类

4.1 List集合子类的特点

  • ArrayList集合

    ​ 底层是数组结构实现,查询快、增删慢

  • LinkedList集合

    ​ 底层是链表结构实现,查询慢、增删快

4.2 集合的案例-ArrayList集合存储学生对象三种方式遍历

  • 案例需求

    ​ 创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合

  • 代码实现

    • 学生类

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      }
      
    • 测试类

      public class ArrayListDemo {
          public static void main(String[] args) {
              //创建ArrayList集合对象
              ArrayList<Student> array = new ArrayList<Student>();
      
              //创建学生对象
              Student s1 = new Student("林青霞", 30);
              Student s2 = new Student("张曼玉", 35);
              Student s3 = new Student("王祖贤", 33);
      
              //把学生添加到集合
              array.add(s1);
              array.add(s2);
              array.add(s3);
      
              //迭代器:集合特有的遍历方式
              Iterator<Student> it = array.iterator();
              while (it.hasNext()) {
                  Student s = it.next();
                  System.out.println(s.getName() + "," + s.getAge());
              }
              System.out.println("--------");
      
              //普通for:带有索引的遍历方式
              for(int i=0; i<array.size(); i++) {
                  Student s = array.get(i);
                  System.out.println(s.getName() + "," + s.getAge());
              }
              System.out.println("--------");
      
              //增强for:最方便的遍历方式
              for(Student s : array) {
                  System.out.println(s.getName() + "," + s.getAge());
              }
          }
      }
      

4.3 LinkedList集合的特有功能

  • 特有方法

    方法名说明
    public void addFirst(E e)在该列表开头插入指定的元素
    public void addLast(E e)将指定的元素追加到此列表的末尾
    public E getFirst()返回此列表中的第一个元素
    public E getLast()返回此列表中的最后一个元素
    public E removeFirst()从此列表中删除并返回第一个元素
    public E removeLast()从此列表中删除并返回最后一个元素

5. Set集合

5.1 Set集合概述和特点

  • Set集合的特点
    • 元素存取无序
    • 没有索引、只能通过迭代器或增强for循环遍历
    • 不能存储重复元素
  • Set集合的基本使用
public class SetDemo {
    public static void main(String[] args) {
        //创建集合对象
        Set<String> set = new HashSet<String>();

        //添加元素
        set.add("hello");
        set.add("world");
        set.add("java");
        //不包含重复元素的集合
        set.add("world");

        //遍历
        for(String s : set) {
            System.out.println(s);
        }
    }
}

5.2 哈希值

  • 哈希值简介

    ​ 是JDK根据对象的地址或者字符串或者数字算出来的int类型的数值

  • 如何获取哈希值

    ​ Object类中的public int hashCode():返回对象的哈希码值

  • 哈希值的特点

    • 同一个对象多次调用hashCode()方法返回的哈希值是相同的
    • 默认情况下,不同对象的哈希值是不同的。而重写hashCode()方法,可以实现让不同对象的哈希值相同
  • 获取哈希值的代码

    • 学生类
    public class Student {
        private String name;
        private int age;
    
        public Student() {
        }
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public int hashCode() {
            return 0;
        }
    }
    
    • 测试类
    public class HashDemo {
        public static void main(String[] args) {
            //创建学生对象
            Student s1 = new Student("林青霞",30);
    
            //同一个对象多次调用hashCode()方法返回的哈希值是相同的
            System.out.println(s1.hashCode()); //1060830840
            System.out.println(s1.hashCode()); //1060830840
            System.out.println("--------");
    
            Student s2 = new Student("林青霞",30);
    
            //默认情况下,不同对象的哈希值是不相同的
            //通过方法重写,可以实现不同对象的哈希值是相同的
            System.out.println(s2.hashCode()); //2137211482
            System.out.println("--------");
    
            System.out.println("hello".hashCode()); //99162322
            System.out.println("world".hashCode()); //113318802
            System.out.println("java".hashCode()); //3254818
    
            System.out.println("world".hashCode()); //113318802
            System.out.println("--------");
    
            System.out.println("重地".hashCode()); //1179395
            System.out.println("通话".hashCode()); //1179395
        }
    }
    

5.3 HashSet集合概述和特点

  • HashSet集合的特点

    • 底层数据结构是哈希表
    • 对集合的迭代顺序不作任何保证,也就是说不保证存储和取出的元素顺序一致
    • 没有带索引的方法,所以不能使用普通for循环遍历
    • 由于是Set集合,所以是不包含重复元素的集合
  • HashSet集合的基本使用

    public class HashSetDemo01 {
        public static void main(String[] args) {
            //创建集合对象
            HashSet<String> hs = new HashSet<String>();
    
            //添加元素
            hs.add("hello");
            hs.add("world");
            hs.add("java");
    
            hs.add("world");
    
            //遍历
            for(String s : hs) {
                System.out.println(s);
            }
        }
    }
    

5.4 HashSet集合保证元素唯一性源码分析

  • HashSet集合保证元素唯一性的原理

    ​ 1.根据对象的哈希值计算存储位置

    ​ 如果当前位置没有元素则直接存入

    ​ 如果当前位置有元素存在,则进入第二步

    ​ 2.当前元素的元素和已经存在的元素比较哈希值

    ​ 如果哈希值不同,则将当前元素进行存储

    ​ 如果哈希值相同,则进入第三步

    ​ 3.通过equals()方法比较两个元素的内容

    ​ 如果内容不相同,则将当前元素进行存储

    ​ 如果内容相同,则不存储当前元素

  • HashSet集合保证元素唯一性的图解

在这里插入图片描述

5.5 常见数据结构之哈希表

在这里插入图片描述

5.6 HashSet集合存储学生对象并遍历

  • 案例需求

    • 创建一个存储学生对象的集合,存储多个学生对象,使用程序实现在控制台遍历该集合
    • 要求:学生对象的成员变量值相同,我们就认为是同一个对象
  • 代码实现

    • 学生类

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      
          @Override
          public boolean equals(Object o) {
              if (this == o) return true;
              if (o == null || getClass() != o.getClass()) return false;
      
              Student student = (Student) o;
      
              if (age != student.age) return false;
              return name != null ? name.equals(student.name) : student.name == null;
          }
      
          @Override
          public int hashCode() {
              int result = name != null ? name.hashCode() : 0;
              result = 31 * result + age;
              return result;
          }
      }
      
    • 测试类

      public class HashSetDemo02 {
          public static void main(String[] args) {
              //创建HashSet集合对象
              HashSet<Student> hs = new HashSet<Student>();
      
              //创建学生对象
              Student s1 = new Student("林青霞", 30);
              Student s2 = new Student("张曼玉", 35);
              Student s3 = new Student("王祖贤", 33);
      
              Student s4 = new Student("王祖贤", 33);
      
              //把学生添加到集合
              hs.add(s1);
              hs.add(s2);
              hs.add(s3);
              hs.add(s4);
      
              //遍历集合(增强for)
              for (Student s : hs) {
                  System.out.println(s.getName() + "," + s.getAge());
              }
          }
      }
      

5.7 LinkedHashSet集合概述和特点

  • LinkedHashSet集合特点

    • 哈希表和链表实现的Set接口,具有可预测的迭代次序
    • 由链表保证元素有序,也就是说元素的存储和取出顺序是一致的
    • 由哈希表保证元素唯一,也就是说没有重复的元素
  • LinkedHashSet集合基本使用

    public class LinkedHashSetDemo {
        public static void main(String[] args) {
            //创建集合对象
            LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();
    
            //添加元素
            linkedHashSet.add("hello");
            linkedHashSet.add("world");
            linkedHashSet.add("java");
    
            linkedHashSet.add("world");
    
            //遍历集合
            for(String s : linkedHashSet) {
                System.out.println(s);
            }
        }
    }
    

6. Set集合排序

6.1 TreeSet集合概述和特点

  • TreeSet集合概述

    • 元素有序,可以按照一定的规则进行排序,具体排序方式取决于构造方法
      • TreeSet():根据其元素的自然排序进行排序
      • TreeSet(Comparator comparator) :根据指定的比较器进行排序
    • 没有带索引的方法,所以不能使用普通for循环遍历
    • 由于是Set集合,所以不包含重复元素的集合
  • TreeSet集合基本使用

    public class TreeSetDemo01 {
        public static void main(String[] args) {
            //创建集合对象
            TreeSet<Integer> ts = new TreeSet<Integer>();
    
            //添加元素
            ts.add(10);
            ts.add(40);
            ts.add(30);
            ts.add(50);
            ts.add(20);
    
            ts.add(30);
    
            //遍历集合
            for(Integer i : ts) {
                System.out.println(i);
            }
        }
    }
    

6.2 自然排序Comparable的使用

  • 案例需求

    • 存储学生对象并遍历,创建TreeSet集合使用无参构造方法
    • 要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
  • 实现步骤

    • 用TreeSet集合存储自定义对象,无参构造方法使用的是自然排序对元素进行排序的
    • 自然排序,就是让元素所属的类实现Comparable接口,重写compareTo(T o)方法
    • 重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件来写
  • 代码实现

    • 学生类

      public class Student implements Comparable<Student> {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      
          @Override
          public int compareTo(Student s) {
      //        return 0;
      //        return 1;
      //        return -1;
              //按照年龄从小到大排序
             int num = this.age - s.age;
      //        int num = s.age - this.age;
              //年龄相同时,按照姓名的字母顺序排序
             int num2 = num==0?this.name.compareTo(s.name):num;
              return num2;
          }
      }
      
    • 测试类

      public class TreeSetDemo02 {
          public static void main(String[] args) {
              //创建集合对象
              TreeSet<Student> ts = new TreeSet<Student>();
      
              //创建学生对象
              Student s1 = new Student("xishi", 29);
              Student s2 = new Student("wangzhaojun", 28);
              Student s3 = new Student("diaochan", 30);
              Student s4 = new Student("yangyuhuan", 33);
      
              Student s5 = new Student("linqingxia",33);
              Student s6 = new Student("linqingxia",33);
      
              //把学生添加到集合
              ts.add(s1);
              ts.add(s2);
              ts.add(s3);
              ts.add(s4);
              ts.add(s5);
              ts.add(s6);
      
              //遍历集合
              for (Student s : ts) {
                  System.out.println(s.getName() + "," + s.getAge());
              }
          }
      }
      

6.3 比较器排序Comparator的使用

  • 案例需求

    • 存储学生对象并遍历,创建TreeSet集合使用带参构造方法
    • 要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
  • 实现步骤

    • 用TreeSet集合存储自定义对象,带参构造方法使用的是比较器排序对元素进行排序的
    • 比较器排序,就是让集合构造方法接收Comparator的实现类对象,重写compare(T o1,T o2)方法
    • 重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件来写
  • 代码实现

    • 学生类

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      }
      
      
    • 测试类

      public class TreeSetDemo {
          public static void main(String[] args) {
              //创建集合对象
              TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
                  @Override
                  public int compare(Student s1, Student s2) {
                      //this.age - s.age
                      //s1,s2
                      int num = s1.getAge() - s2.getAge();
                      int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
                      return num2;
                  }
              });
      
              //创建学生对象
              Student s1 = new Student("xishi", 29);
              Student s2 = new Student("wangzhaojun", 28);
              Student s3 = new Student("diaochan", 30);
              Student s4 = new Student("yangyuhuan", 33);
      
              Student s5 = new Student("linqingxia",33);
              Student s6 = new Student("linqingxia",33);
      
              //把学生添加到集合
              ts.add(s1);
              ts.add(s2);
              ts.add(s3);
              ts.add(s4);
              ts.add(s5);
              ts.add(s6);
      
              //遍历集合
              for (Student s : ts) {
                  System.out.println(s.getName() + "," + s.getAge());
              }
          }
      }
      
      

6.4 成绩排序案例

  • 案例需求

    • 用TreeSet集合存储多个学生信息(姓名,语文成绩,数学成绩),并遍历该集合
    • 要求:按照总分从高到低出现
  • 代码实现

    • 学生类

       public class Student {
          private String name;
          private int chinese;
          private int math;
      
          public Student() {
          }
      
          public Student(String name, int chinese, int math) {
              this.name = name;
              this.chinese = chinese;
              this.math = math;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getChinese() {
              return chinese;
          }
      
          public void setChinese(int chinese) {
              this.chinese = chinese;
          }
      
          public int getMath() {
              return math;
          }
      
          public void setMath(int math) {
              this.math = math;
          }
      
          public int getSum() {
              return this.chinese + this.math;
          }
      }
      
    • 测试类

      public class TreeSetDemo {
          public static void main(String[] args) {
              //创建TreeSet集合对象,通过比较器排序进行排序
              TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
                  @Override
                  public int compare(Student s1, Student s2) {
      //                int num = (s2.getChinese()+s2.getMath())-(s1.getChinese()+s1.getMath());
                      //主要条件
                      int num = s2.getSum() - s1.getSum();
                      //次要条件
                      int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
                      int num3 = num2 == 0 ? s1.getName().compareTo(s2.getName()) : num2;
                      return num3;
                  }
              });
      
              //创建学生对象
              Student s1 = new Student("林青霞", 98, 100);
              Student s2 = new Student("张曼玉", 95, 95);
              Student s3 = new Student("王祖贤", 100, 93);
              Student s4 = new Student("柳岩", 100, 97);
              Student s5 = new Student("风清扬", 98, 98);
      
              Student s6 = new Student("左冷禅", 97, 99);
      //        Student s7 = new Student("左冷禅", 97, 99);
              Student s7 = new Student("赵云", 97, 99);
      
              //把学生对象添加到集合
              ts.add(s1);
              ts.add(s2);
              ts.add(s3);
              ts.add(s4);
              ts.add(s5);
              ts.add(s6);
              ts.add(s7);
      
              //遍历集合
              for (Student s : ts) {
                  System.out.println(s.getName() + "," + s.getChinese() + "," + s.getMath() + "," + s.getSum());
              }
          }
      }
      
      

6.5 不重复的随机数案例

  • 案例需求

    • 编写一个程序,获取10个1-20之间的随机数,要求随机数不能重复,并在控制台输出
  • 代码实现

      public class SetDemo {
          public static void main(String[] args) {
              //创建Set集合对象
      //        Set<Integer> set = new HashSet<Integer>();
              Set<Integer> set = new TreeSet<Integer>();
      
              //创建随机数对象
              Random r = new Random();
      
              //判断集合的长度是不是小于10
              while (set.size()<10) {
                  //产生一个随机数,添加到集合
                  int number = r.nextInt(20) + 1;
                  set.add(number);
              }
      
              //遍历集合
              for(Integer i : set) {
                  System.out.println(i);
              }
          }
      }
    

7. 泛型

7.1 泛型概述和好处

  • 泛型概述

    ​ 是JDK5中引入的特性,它提供了编译时类型安全检测机制,该机制允许在编译时检测到非法的类型

    它的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数。一提到参数,最熟悉的就是定义方法时有形参,然后调用此方法时传递实参。那么参数化类型怎么理解呢?顾名思义,就是将类型由原来的具体的类型参数化,然后在使用/调用时传入具体的类型。这种参数类型可以用在类、方法和接口中,分别被称为泛型类、泛型方法、泛型接口

  • 泛型定义格式

    • <类型>:指定一种类型的格式。这里的类型可以看成是形参
    • <类型1,类型2…>:指定多种类型的格式,多种类型之间用逗号隔开。这里的类型可以看成是形参
    • 将来具体调用时候给定的类型可以看成是实参,并且实参的类型只能是引用数据类型
  • 泛型的好处

    • 把运行时期的问题提前到了编译期间
    • 避免了强制类型转换

7.2 泛型类

  • 定义格式

    修饰符 class 类名<类型> {  }
    
  • 示例代码

    • 泛型类

      public class Generic<T> {
          private T t;
      
          public T getT() {
              return t;
          }
      
          public void setT(T t) {
              this.t = t;
          }
      }
      
    • 测试类

      public class GenericDemo {
          public static void main(String[] args) {
              Student s = new Student();
              s.setName("林青霞");
              System.out.println(s.getName());
      
              Teacher t = new Teacher();
              t.setAge(30);
      		//t.setAge("30");
              System.out.println(t.getAge());
              System.out.println("--------");
      
              Generic<String> g1 = new Generic<String>();
              g1.setT("林青霞");
              System.out.println(g1.getT());
      
              Generic<Integer> g2 = new Generic<Integer>();
              g2.setT(30);
              System.out.println(g2.getT());
      
              Generic<Boolean> g3 = new Generic<Boolean>();
              g3.setT(true);
              System.out.println(g3.getT());
          }
      }
      

7.3 泛型方法

  • 定义格式

    修饰符 <类型> 返回值类型 方法名(类型 变量名) {  }
    
  • 示例代码

    • 带有泛型方法的类

      public class Generic {
          public <T> void show(T t) {
              System.out.println(t);
          }
      }
      
    • 测试类

      public class GenericDemo {
          public static void main(String[] args) {
      
              Generic g = new Generic();
              g.show("林青霞");
              g.show(30);
              g.show(true);
              g.show(12.34);
          }
      }
      

7.4 泛型接口

  • 定义格式

    修饰符 interface 接口名<类型> {  }
    
  • 示例代码

    • 泛型接口

      public interface Generic<T> {
          void show(T t);
      }
      
    • 泛型接口实现类

      public class GenericImpl<T> implements Generic<T> {
          @Override
          public void show(T t) {
              System.out.println(t);
          }
      }
      
      
    • 测试类

      public class GenericDemo {
          public static void main(String[] args) {
              Generic<String> g1 = new GenericImpl<String>();
              g1.show("林青霞");
      
              Generic<Integer> g2 = new GenericImpl<Integer>();
              g2.show(30);
          }
      }
      

7.5 类型通配符

  • 类型通配符的作用

    ​ 为了表示各种泛型List的父类,可以使用类型通配符

  • 类型通配符的分类

    • 类型通配符:<?>
      • List<?>:表示元素类型未知的List,它的元素可以匹配任何的类型
      • 这种带通配符的List仅表示它是各种泛型List的父类,并不能把元素添加到其中
    • 类型通配符上限:<? extends 类型>
      • List<? extends Number>:它表示的类型是Number或者其子类型
    • 类型通配符下限:<? super 类型>
      • List<? super Number>:它表示的类型是Number或者其父类型
  • 类型通配符的基本使用

      public class GenericDemo {
          public static void main(String[] args) {
              //类型通配符:<?>
              List<?> list1 = new ArrayList<Object>();
              List<?> list2 = new ArrayList<Number>();
              List<?> list3 = new ArrayList<Integer>();
              System.out.println("--------");
      
              //类型通配符上限:<? extends 类型>
      //        List<? extends Number> list4 = new ArrayList<Object>();
              List<? extends Number> list5 = new ArrayList<Number>();
              List<? extends Number> list6 = new ArrayList<Integer>();
              System.out.println("--------");
      
              //类型通配符下限:<? super 类型>
              List<? super Number> list7 = new ArrayList<Object>();
              List<? super Number> list8 = new ArrayList<Number>();
      //        List<? super Number> list9 = new ArrayList<Integer>();
      
          }
      }
    

8. 可变参数

8.1 可变参数

  • 可变参数介绍

    ​ 可变参数又称参数个数可变,用作方法的形参出现,那么方法参数个数就是可变的了

  • 可变参数定义格式

    修饰符 返回值类型 方法名(数据类型… 变量名) {  }
    
  • 可变参数的注意事项

    • 这里的变量其实是一个数组
    • 如果一个方法有多个参数,包含可变参数,可变参数要放在最后
  • 可变参数的基本使用

    public class ArgsDemo01 {
        public static void main(String[] args) {
            System.out.println(sum(10, 20));
            System.out.println(sum(10, 20, 30));
            System.out.println(sum(10, 20, 30, 40));
    
            System.out.println(sum(10,20,30,40,50));
            System.out.println(sum(10,20,30,40,50,60));
            System.out.println(sum(10,20,30,40,50,60,70));
            System.out.println(sum(10,20,30,40,50,60,70,80,90,100));
        }
    
    //    public static int sum(int b,int... a) {
    //        return 0;
    //    }
    
        public static int sum(int... a) {
            int sum = 0;
            for(int i : a) {
                sum += i;
            }
            return sum;
        }
    }
    

8.2 可变参数的使用

  • Arrays工具类中有一个静态方法:

    • public static List asList(T… a):返回由指定数组支持的固定大小的列表
    • 返回的集合不能做增删操作,可以做修改操作
  • List接口中有一个静态方法:

    • public static List of(E… elements):返回包含任意数量元素的不可变列表
    • 返回的集合不能做增删改操作
  • Set接口中有一个静态方法:

    • public static Set of(E… elements) :返回一个包含任意数量元素的不可变集合
    • 在给元素的时候,不能给重复的元素
    • 返回的集合不能做增删操作,没有修改的方法
  • 示例代码

    public class ArgsDemo02 {
        public static void main(String[] args) {
            //public static <T> List<T> asList(T... a):返回由指定数组支持的固定大小的列表
    //        List<String> list = Arrays.asList("hello", "world", "java");
    //
            list.add("javaee"); //UnsupportedOperationException
            list.remove("world"); //UnsupportedOperationException
    //        list.set(1,"javaee");
    //
    //        System.out.println(list);
    
            //public static <E> List<E> of(E... elements):返回包含任意数量元素的不可变列表
    //        List<String> list = List.of("hello", "world", "java", "world");
    //
            list.add("javaee");//UnsupportedOperationException
            list.remove("java");//UnsupportedOperationException
            list.set(1,"javaee");//UnsupportedOperationException
    //
    //        System.out.println(list);
    
            //public static <E> Set<E> of(E... elements) :返回一个包含任意数量元素的不可变集合
    //        Set<String> set = Set.of("hello", "world", "java","world"); //IllegalArgumentException
            //Set<String> set = Set.of("hello", "world", "java");
    
    //        set.add("javaee");//UnsupportedOperationException
    //        set.remove("world");//UnsupportedOperationException
    
            //System.out.println(set);
        }
    }
    

9. Map集合

9.1 Map集合概述和特点

  • Map集合概述

    interface Map<K,V>  K:键的类型;V:值的类型
    
  • Map集合的特点

    • 键值对映射关系
    • 一个键对应一个值
    • 键不能重复,值可以重复
    • 元素存取无序
  • Map集合的基本使用

    public class MapDemo01 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String,String> map = new HashMap<String,String>();
    
            //V put(K key, V value) 将指定的值与该映射中的指定键相关联
            map.put("itheima001","林青霞");
            map.put("itheima002","张曼玉");
            map.put("itheima003","王祖贤");
            map.put("itheima003","柳岩");
    
            //输出集合对象
            System.out.println(map);
        }
    }
    

9.2 Map集合的基本功能

  • 方法介绍

    方法名说明
    V put(K key,V value)添加元素
    V remove(Object key)根据键删除键值对元素
    void clear()移除所有的键值对元素
    boolean containsKey(Object key)判断集合是否包含指定的键
    boolean containsValue(Object value)判断集合是否包含指定的值
    boolean isEmpty()判断集合是否为空
    int size()集合的长度,也就是集合中键值对的个数
  • 示例代码

    public class MapDemo02 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String,String> map = new HashMap<String,String>();
    
            //V put(K key,V value):添加元素
            map.put("张无忌","赵敏");
            map.put("郭靖","黄蓉");
            map.put("杨过","小龙女");
    
            //V remove(Object key):根据键删除键值对元素
    //        System.out.println(map.remove("郭靖"));
    //        System.out.println(map.remove("郭襄"));
    
            //void clear():移除所有的键值对元素
    //        map.clear();
    
            //boolean containsKey(Object key):判断集合是否包含指定的键
    //        System.out.println(map.containsKey("郭靖"));
    //        System.out.println(map.containsKey("郭襄"));
    
            //boolean isEmpty():判断集合是否为空
    //        System.out.println(map.isEmpty());
    
            //int size():集合的长度,也就是集合中键值对的个数
            System.out.println(map.size());
    
    
            //输出集合对象
            System.out.println(map);
        }
    }
    

9.3 Map集合的获取功能

  • 方法介绍

    方法名说明
    V get(Object key)根据键获取值
    Set keySet()获取所有键的集合
    Collection values()获取所有值的集合
    Set<Map.Entry<K,V>> entrySet()获取所有键值对对象的集合
  • 示例代码

    public class MapDemo03 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String, String> map = new HashMap<String, String>();
    
            //添加元素
            map.put("张无忌", "赵敏");
            map.put("郭靖", "黄蓉");
            map.put("杨过", "小龙女");
    
            //V get(Object key):根据键获取值
    //        System.out.println(map.get("张无忌"));
    //        System.out.println(map.get("张三丰"));
    
            //Set<K> keySet():获取所有键的集合
    //        Set<String> keySet = map.keySet();
    //        for(String key : keySet) {
    //            System.out.println(key);
    //        }
    
            //Collection<V> values():获取所有值的集合
            Collection<String> values = map.values();
            for(String value : values) {
                System.out.println(value);
            }
        }
    }
    

9.4 Map集合的遍历(方式1)

  • 遍历思路

    • 我们刚才存储的元素都是成对出现的,所以我们把Map看成是一个夫妻对的集合
      • 把所有的丈夫给集中起来
      • 遍历丈夫的集合,获取到每一个丈夫
      • 根据丈夫去找对应的妻子
  • 步骤分析

    • 获取所有键的集合。用keySet()方法实现
    • 遍历键的集合,获取到每一个键。用增强for实现
    • 根据键去找值。用get(Object key)方法实现
  • 代码实现

    public class MapDemo01 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String, String> map = new HashMap<String, String>();
    
            //添加元素
            map.put("张无忌", "赵敏");
            map.put("郭靖", "黄蓉");
            map.put("杨过", "小龙女");
    
            //获取所有键的集合。用keySet()方法实现
            Set<String> keySet = map.keySet();
            //遍历键的集合,获取到每一个键。用增强for实现
            for (String key : keySet) {
                //根据键去找值。用get(Object key)方法实现
                String value = map.get(key);
                System.out.println(key + "," + value);
            }
        }
    }
    

9.5 Map集合的遍历(方式2)

  • 遍历思路

    • 我们刚才存储的元素都是成对出现的,所以我们把Map看成是一个夫妻对的集合
      • 获取所有结婚证的集合
      • 遍历结婚证的集合,得到每一个结婚证
      • 根据结婚证获取丈夫和妻子
  • 步骤分析

    • 获取所有键值对对象的集合
      • Set<Map.Entry<K,V>> entrySet():获取所有键值对对象的集合
    • 遍历键值对对象的集合,得到每一个键值对对象
      • 用增强for实现,得到每一个Map.Entry
    • 根据键值对对象获取键和值
      • 用getKey()得到键
      • 用getValue()得到值
  • 代码实现

    public class MapDemo02 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String, String> map = new HashMap<String, String>();
    
            //添加元素
            map.put("张无忌", "赵敏");
            map.put("郭靖", "黄蓉");
            map.put("杨过", "小龙女");
    
            //获取所有键值对对象的集合
            Set<Map.Entry<String, String>> entrySet = map.entrySet();
            //遍历键值对对象的集合,得到每一个键值对对象
            for (Map.Entry<String, String> me : entrySet) {
                //根据键值对对象获取键和值
                String key = me.getKey();
                String value = me.getValue();
                System.out.println(key + "," + value);
            }
        }
    }
    

9.6 Map集合的案例

9.6.1 HashMap集合练习之键是String值是Student

  • 案例需求

    ​ 创建一个HashMap集合,键是学号(String),值是学生对象(Student)。存储三个键值对元素,并遍历

  • 代码实现

    • 学生类

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      }
      
    • 测试类

      /*
          需求:
              创建一个HashMap集合,键是学号(String),值是学生对象(Student)。存储三个键值对元素,并遍历
      
          思路:
              1:定义学生类
              2:创建HashMap集合对象
              3:创建学生对象
              4:把学生添加到集合
              5:遍历集合
                  方式1:键找值
                  方式2:键值对对象找键和值
       */
      public class HashMapDemo {
          public static void main(String[] args) {
              //创建HashMap集合对象
              HashMap<String, Student> hm = new HashMap<String, Student>();
      
              //创建学生对象
              Student s1 = new Student("林青霞", 30);
              Student s2 = new Student("张曼玉", 35);
              Student s3 = new Student("王祖贤", 33);
      
              //把学生添加到集合
              hm.put("itheima001", s1);
              hm.put("itheima002", s2);
              hm.put("itheima003", s3);
      
              //方式1:键找值
              Set<String> keySet = hm.keySet();
              for (String key : keySet) {
                  Student value = hm.get(key);
                  System.out.println(key + "," + value.getName() + "," + value.getAge());
              }
              System.out.println("--------");
      
              //方式2:键值对对象找键和值
              Set<Map.Entry<String, Student>> entrySet = hm.entrySet();
              for (Map.Entry<String, Student> me : entrySet) {
                  String key = me.getKey();
                  Student value = me.getValue();
                  System.out.println(key + "," + value.getName() + "," + value.getAge());
              }
          }
      }
      

9.6.2 HashMap集合练习之键是Student值是String

  • 案例需求

    • 创建一个HashMap集合,键是学生对象(Student),值是居住地 (String)。存储多个元素,并遍历。
    • 要求保证键的唯一性:如果学生对象的成员变量值相同,我们就认为是同一个对象
  • 代码实现

    • 学生类

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      
          @Override
          public boolean equals(Object o) {
              if (this == o) return true;
              if (o == null || getClass() != o.getClass()) return false;
      
              Student student = (Student) o;
      
              if (age != student.age) return false;
              return name != null ? name.equals(student.name) : student.name == null;
          }
      
          @Override
          public int hashCode() {
              int result = name != null ? name.hashCode() : 0;
              result = 31 * result + age;
              return result;
          }
      }
      
    • 测试类

      public class HashMapDemo {
          public static void main(String[] args) {
              //创建HashMap集合对象
              HashMap<Student, String> hm = new HashMap<Student, String>();
      
              //创建学生对象
              Student s1 = new Student("林青霞", 30);
              Student s2 = new Student("张曼玉", 35);
              Student s3 = new Student("王祖贤", 33);
              Student s4 = new Student("王祖贤", 33);
      
              //把学生添加到集合
              hm.put(s1, "西安");
              hm.put(s2, "武汉");
              hm.put(s3, "郑州");
              hm.put(s4, "北京");
      
              //遍历集合
              Set<Student> keySet = hm.keySet();
              for (Student key : keySet) {
                  String value = hm.get(key);
                  System.out.println(key.getName() + "," + key.getAge() + "," + value);
              }
          }
      }
      

9.6.3 集合嵌套之ArrayList嵌套HashMap

  • 案例需求

    • 创建一个ArrayList集合,存储三个元素,每一个元素都是HashMap
    • 每一个HashMap的键和值都是String,并遍历。
  • 代码实现

      public class ArrayListIncludeHashMapDemo {
          public static void main(String[] args) {
              //创建ArrayList集合
              ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String, String>>();
      
              //创建HashMap集合,并添加键值对元素
              HashMap<String, String> hm1 = new HashMap<String, String>();
              hm1.put("孙策", "大乔");
              hm1.put("周瑜", "小乔");
              //把HashMap作为元素添加到ArrayList集合
              array.add(hm1);
      
              HashMap<String, String> hm2 = new HashMap<String, String>();
              hm2.put("郭靖", "黄蓉");
              hm2.put("杨过", "小龙女");
              //把HashMap作为元素添加到ArrayList集合
              array.add(hm2);
      
              HashMap<String, String> hm3 = new HashMap<String, String>();
              hm3.put("令狐冲", "任盈盈");
              hm3.put("林平之", "岳灵珊");
              //把HashMap作为元素添加到ArrayList集合
              array.add(hm3);
      
              //遍历ArrayList集合
              for (HashMap<String, String> hm : array) {
                  Set<String> keySet = hm.keySet();
                  for (String key : keySet) {
                      String value = hm.get(key);
                      System.out.println(key + "," + value);
                  }
              }
          }
      }
    

9.6.4 集合嵌套之HashMap嵌套ArrayList

  • 案例需求

    • 创建一个HashMap集合,存储三个键值对元素,每一个键值对元素的键是String,值是ArrayList
    • 每一个ArrayList的元素是String,并遍历。
  • 代码实现

      public class HashMapIncludeArrayListDemo {
          public static void main(String[] args) {
              //创建HashMap集合
              HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
      
              //创建ArrayList集合,并添加元素
              ArrayList<String> sgyy = new ArrayList<String>();
              sgyy.add("诸葛亮");
              sgyy.add("赵云");
              //把ArrayList作为元素添加到HashMap集合
              hm.put("三国演义",sgyy);
      
              ArrayList<String> xyj = new ArrayList<String>();
              xyj.add("唐僧");
              xyj.add("孙悟空");
              //把ArrayList作为元素添加到HashMap集合
              hm.put("西游记",xyj);
      
              ArrayList<String> shz = new ArrayList<String>();
              shz.add("武松");
              shz.add("鲁智深");
              //把ArrayList作为元素添加到HashMap集合
              hm.put("水浒传",shz);
      
              //遍历HashMap集合
              Set<String> keySet = hm.keySet();
              for(String key : keySet) {
                  System.out.println(key);
                  ArrayList<String> value = hm.get(key);
                  for(String s : value) {
                      System.out.println("\t" + s);
                  }
              }
          }
      }
    

9.6.5 统计字符串中每个字符出现的次数

  • 案例需求

    • 键盘录入一个字符串,要求统计字符串中每个字符串出现的次数。
    • 举例:键盘录入“aababcabcdabcde” 在控制台输出:“a(5)b(4)c(3)d(2)e(1)”
  • 代码实现

    public class HashMapDemo {    public static void main(String[] args) {        //键盘录入一个字符串        Scanner sc = new Scanner(System.in);        System.out.println("请输入一个字符串:");        String line = sc.nextLine();        //创建HashMap集合,键是Character,值是Integer//        HashMap<Character, Integer> hm = new HashMap<Character, Integer>();        TreeMap<Character, Integer> hm = new TreeMap<Character, Integer>();        //遍历字符串,得到每一个字符        for (int i = 0; i < line.length(); i++) {            char key = line.charAt(i);            //拿得到的每一个字符作为键到HashMap集合中去找对应的值,看其返回值            Integer value = hm.get(key);            if (value == null) {                //如果返回值是null:说明该字符在HashMap集合中不存在,就把该字符作为键,1作为值存储                hm.put(key,1);            } else {                //如果返回值不是null:说明该字符在HashMap集合中存在,把该值加1,然后重新存储该字符和对应的值                value++;                hm.put(key,value);            }        }        //遍历HashMap集合,得到键和值,按照要求进行拼接        StringBuilder sb = new StringBuilder();        Set<Character> keySet = hm.keySet();        for(Character key : keySet) {            Integer value = hm.get(key);            sb.append(key).append("(").append(value).append(")");        }        String result = sb.toString();        //输出结果        System.out.println(result);    }}
    

10. Collections集合工具类

10.1 Collections概述和使用

  • Collections类的作用

    ​ 是针对集合操作的工具类

  • Collections类常用方法

    方法名说明
    public static void sort(List list)将指定的列表按升序排序
    public static void reverse(List<?> list)反转指定列表中元素的顺序
    public static void shuffle(List<?> list)使用默认的随机源随机排列指定的列表
  • 示例代码

      public class CollectionsDemo01 {
          public static void main(String[] args) {
              //创建集合对象
              List<Integer> list = new ArrayList<Integer>();
      
              //添加元素
              list.add(30);
              list.add(20);
              list.add(50);
              list.add(10);
              list.add(40);
      
              //public static <T extends Comparable<? super T>> void sort(List<T> list):将指定的列表按升序排序
      //        Collections.sort(list);
      
              //public static void reverse(List<?> list):反转指定列表中元素的顺序
      //        Collections.reverse(list);
      
              //public static void shuffle(List<?> list):使用默认的随机源随机排列指定的列表
              Collections.shuffle(list);
      
              System.out.println(list);
          }
      }
    

10.2 ArrayList集合存储学生并排序

  • 案例需求

    • ArrayList存储学生对象,使用Collections对ArrayList进行排序
    • 要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
  • 代码实现

    • 学生类

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      }
      
      
    • 测试类

      public class CollectionsDemo02 {
          public static void main(String[] args) {
              //创建ArrayList集合对象
              ArrayList<Student> array = new ArrayList<Student>();
      
              //创建学生对象
              Student s1 = new Student("linqingxia", 30);
              Student s2 = new Student("zhangmanyu", 35);
              Student s3 = new Student("wangzuxian", 33);
              Student s4 = new Student("liuyan", 33);
      
              //把学生添加到集合
              array.add(s1);
              array.add(s2);
              array.add(s3);
              array.add(s4);
      
              //使用Collections对ArrayList集合排序
              //sort(List<T> list, Comparator<? super T> c)
              Collections.sort(array, new Comparator<Student>() {
                  @Override
                  public int compare(Student s1, Student s2) {
                      //按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
                      int num = s1.getAge() - s2.getAge();
                      int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
                      return num2;
                  }
              });
      
              //遍历集合
              for (Student s : array) {
                  System.out.println(s.getName() + "," + s.getAge());
              }
      
          }
      }
      

11. 斗地主案例

11.1 模拟斗地主案例-普通版本

  • 案例需求

    ​ 通过程序实现斗地主过程中的洗牌,发牌和看牌

  • 代码实现

      public class PokerDemo {
          public static void main(String[] args) {
              //创建一个牌盒,也就是定义一个集合对象,用ArrayList集合实现
              ArrayList<String> array = new ArrayList<String>();
      
              //往牌盒里面装牌
              /*
                  ♦2,♦3,♦4...♦K,♦A
                  ♣2,...
                  ♥2,...
                  ♠2,...
                  小王,大王
               */
              //定义花色数组
              String[] colors = {"♦", "♣", "♥", "♠"};
              //定义点数数组
              String[] numbers = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
              for (String color : colors) {
                  for (String number : numbers) {
                      array.add(color + number);
                  }
              }
              array.add("小王");
              array.add("大王");
      
              //洗牌,也就是把牌打撒,用Collections的shuffle()方法实现
              Collections.shuffle(array);
      
      //        System.out.println(array);
      
              //发牌,也就是遍历集合,给三个玩家发牌
              ArrayList<String> lqxArray = new ArrayList<String>();
              ArrayList<String> lyArray = new ArrayList<String>();
              ArrayList<String> fqyArray = new ArrayList<String>();
              ArrayList<String> dpArray = new ArrayList<String>();
      
              for (int i = 0; i < array.size(); i++) {
                  String poker = array.get(i);
                  if (i >= array.size() - 3) {
                      dpArray.add(poker);
                  } else if (i % 3 == 0) {
                      lqxArray.add(poker);
                  } else if (i % 3 == 1) {
                      lyArray.add(poker);
                  } else if (i % 3 == 2) {
                      fqyArray.add(poker);
                  }
              }
      
              //看牌,也就是三个玩家分别遍历自己的牌
              lookPoker("林青霞", lqxArray);
              lookPoker("柳岩", lyArray);
              lookPoker("风清扬", fqyArray);
              lookPoker("底牌", dpArray);
          }
      
          //看牌的方法
          public static void lookPoker(String name, ArrayList<String> array) {
              System.out.print(name + "的牌是:");
              for (String poker : array) {
                  System.out.print(poker + " ");
              }
              System.out.println();
          }
      }
    
    

11.2 模拟斗地主案例-升级版本

  • 案例需求

    ​ 通过程序实现斗地主过程中的洗牌,发牌和看牌。要求:对牌进行排序

  • 代码实现

      public class PokerDemo {
          public static void main(String[] args) {
              //创建HashMap,键是编号,值是牌
              HashMap<Integer, String> hm = new HashMap<Integer, String>();
      
              //创建ArrayList,存储编号
              ArrayList<Integer> array = new ArrayList<Integer>();
      
              //创建花色数组和点数数组
              String[] colors = {"♦", "♣", "♥", "♠"};
              String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
      
              //从0开始往HashMap里面存储编号,并存储对应的牌。同时往ArrayList里面存储编号
              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);
              index++;
              hm.put(index, "大王");
              array.add(index);
      
              //洗牌(洗的是编号),用Collections的shuffle()方法实现
              Collections.shuffle(array);
      
              //发牌(发的也是编号,为了保证编号是排序的,创建TreeSet集合接收)
              TreeSet<Integer> lqxSet = new TreeSet<Integer>();
              TreeSet<Integer> lySet = new TreeSet<Integer>();
              TreeSet<Integer> fqySet = new TreeSet<Integer>();
              TreeSet<Integer> dpSet = new TreeSet<Integer>();
      
              for (int i = 0; i < array.size(); i++) {
                  int x = array.get(i);
                  if (i >= array.size() - 3) {
                      dpSet.add(x);
                  } else if (i % 3 == 0) {
                      lqxSet.add(x);
                  } else if (i % 3 == 1) {
                      lySet.add(x);
                  } else if (i % 3 == 2) {
                      fqySet.add(x);
                  }
              }
      
              //调用看牌方法
              lookPoker("林青霞", lqxSet, hm);
              lookPoker("柳岩", lySet, hm);
              lookPoker("风清扬", fqySet, hm);
              lookPoker("底牌", dpSet, hm);
          }
      
          //定义方法看牌(遍历TreeSet集合,获取编号,到HashMap集合找对应的牌)
          public static void lookPoker(String name, TreeSet<Integer> ts, HashMap<Integer, String> hm) {
              System.out.print(name + "的牌是:");
              for (Integer key : ts) {
                  String poker = hm.get(key);
                  System.out.print(poker + " ");
              }
              System.out.println();
          }
      }
    
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java集合篇 的相关文章

  • 如何在日期选择器中设置不在当前月份的单元格的样式

    我目前正在为我的 JavaFX 应用程序制作注册表 问题是 当日期选择器中的单元格不在页面的月份上时 我想让该单元格变灰 让我们看看我当前的日期选择器 我的日期选择器 正如您所看到的 我希望下个月的日期 27 日 28 日 30 日以及 1
  • JavaMail Gmail 问题。 “准备启动 TLS”然后失败

    mailServerProperties System getProperties mailServerProperties put mail smtp port 587 mailServerProperties put mail smtp
  • 在Windows上安装Java 11 OpenJDK(系统路径问题)

    Java 11 最近发布了 众所周知 这个版本没有安装文件 当然 要在没有安装程序的情况下安装 Java 我将系统设置 PATH 和 JAVA HOME 设置为解压缩 Java 11 的文件夹的地址 根据对类似问题的已接受回复建议 唯一的事
  • JNI 不满意链接错误

    我想创建一个简单的 JNI 层 我使用Visual studio 2008创建了一个dll Win 32控制台应用程序项目类型 带有DLL作为选项 当我调用本机方法时 出现此异常 Exception occurred during even
  • CXF Swagger2功能添加安全定义

    我想使用 org apache cxf jaxrs swagger Swagger2Feature 将安全定义添加到我的其余服务中 但是我看不到任何相关方法或任何有关如何执行此操作的资源 下面是我想使用 swagger2feature 生成
  • 在浏览器中点击应用程序时播放框架挂起

    我正在 Play 中运行一个应用程序activator run 也许 5 次中有 3 次 它会挂起 当我去http localhost 9000 它就永远坐在那里旋转 我看到很多promise timed out错误也 我应该去哪里寻找这个
  • java中删除字符串中的特殊字符?

    如何删除字符串中除 之外的特殊字符 现在我用 replaceAll w s 它删除了所有特殊字符 但我想保留 谁能告诉我我该怎么办 Use replaceAll w s 我所做的是将下划线和连字符添加到正则表达式中 我添加了一个 连字符之前
  • 如何在 Java 中禁用 System.out 以提高速度

    我正在用 Java 编写一个模拟重力的程序 其中有一堆日志语句 到 System out 我的程序运行速度非常慢 我认为日志记录可能是部分原因 有什么方法可以禁用 System out 以便我的程序在打印时不会变慢 或者我是否必须手动检查并
  • 如何在jsp代码中导入java库?

    我有以下jsp代码 我想添加 java io 等库 我怎样才能做到这一点
  • 如何将文件透明地传输到浏览器?

    受控环境 IE8 IIS 7 ColdFusion 当从 IE 发出指向媒体文件 例如 mp3 mpeg 等 的 GET 请求时 浏览器将启动关联的应用程序 Window Media Player 我猜测 IIS 提供文件的方式允许应用程序
  • 从 android 简单上传到 S3

    我在网上搜索了从 android 上传简单文件到 s3 的方法 但找不到任何有效的方法 我认为这是因为缺乏具体步骤 1 https mobile awsblog com post Tx1V588RKX5XPQB TransferManage
  • Spring Data 与 Spring Data JPA 与 JdbcTemplate

    我有信心Spring Data and Spring Data JPA指的是相同的 但后来我在 youtube 上观看了一个关于他正在使用JdbcTemplate在那篇教程中 所以我在那里感到困惑 我想澄清一下两者之间有什么区别Spring
  • 归并排序中的递归:两次递归调用

    private void mergesort int low int high line 1 if low lt high line 2 int middle low high 2 line 3 mergesort low middle l
  • Java直接内存:在自定义类中使用sun.misc.Cleaner

    在 Java 中 NIO 直接缓冲区分配的内存通过以下方式释放 sun misc Cleaner实例 一些比对象终结更有效的特殊幻像引用 这种清洁器机制是否仅针对直接缓冲区子类硬编码在 JVM 中 或者是否也可以在自定义组件中使用清洁器 例
  • 将多模块 Maven 项目导入 Eclipse 时出现问题 (STS 2.5.2)

    我刚刚花了最后一个小时查看 Stackoverflow com 上的线程 尝试将 Maven 项目导入到 Spring ToolSuite 2 5 2 中 Maven 项目有多个模块 当我使用 STS 中的 Import 向导导入项目时 所
  • Java中未绑定通配符泛型的用途和要点是什么?

    我不明白未绑定通配符泛型有什么用 具有上限的绑定通配符泛型 stuff for Object item stuff System out println item Since PrintStream println 可以处理所有引用类型 通
  • 如何在 Maven 中显示消息

    如何在 Maven 中显示消息 在ant中 我们确实有 echo 来显示消息 但是在maven中 我该怎么做呢 您可以使用 antrun 插件
  • Android JNI C 简单追加函数

    我想制作一个简单的函数 返回两个字符串的值 基本上 java public native String getAppendedString String name c jstring Java com example hellojni He
  • 查看Jasper报告执行的SQL

    运行 Jasper 报表 其中 SQL 嵌入到报表文件 jrxml 中 时 是否可以看到执行的 SQL 理想情况下 我还想查看替换每个 P 占位符的值 Cheers Don JasperReports 使用 Jakarta Commons
  • com.jcraft.jsch.JSchException:身份验证失败

    当我从本地磁盘上传文件到远程服务器时 出现这样的异常 com jcraft jsch JSchException Auth fail at org apache tools ant taskdefs optional ssh Scp exe

随机推荐

  • ubuntu16.04 安装配置python3.6

    在Ubuntu下 xff0c 时不时会有这个错误的 add apt repository command not found 这个是缺少程序 xff0c 安装一下就可以了 只是不知道安装的名字 按以下命令走一趟就可以的了 sudo apt
  • 最新最快最简单解决rosdep更新失败问题

    在安装ros的时候 xff0c 最后一步会由于源在国外 xff0c sudo rosdep init会失败 xff0c 其中一种方式是通过加https ghproxy com 代理的方式 xff0c 参考链接 我之前也都是这样做的 xff0
  • 解决wsl无法同步本地代理的dns信息

    问题 本地开了公司的vpn xff0c 使用vscode的remote wsl插件连接wsl1 xff0c 结果wsl里面无法解析公司内部的一些域名 xff0c 查了下发现原来是wsl无法自动同步本地代理的dns信息 wsl2没有这个问题
  • 如何在Oracle官网下载jdk

    Oracle官方网址 xff1a Oracle Cloud Applications and Cloud Platform 注册账号 xff1a 登录进入首页 xff1a 点击Products xff1a 来到Products页面 xff0
  • ubuntu安装字体

    先安装 span class token function sudo span span class token function apt get span span class token function install span y
  • windows 压缩指定目录下每个目录和文件为zip文件的powershell脚本

    某个文件夹下有几十个子文件夹 xff0c 想要单个压缩每个子文件夹备份到云盘 如果手动操作会有点累 xff0c 尝试写个脚本吧 版本 适用于win10 win11 其他版本未测试 一 编写脚本 众所周知windows下有两种自带脚本cmd和
  • SpringMVC的配置和执行流程

    要想成功的配置和调试springmvc xff0c 了解掌握它的执行流程是必不可少的 xff0c 话不多说 xff0c 看下图 xff1a 我们边说执行边讲配置 xff0c 首先 xff0c 想要使用springmvc xff0c 依赖是必
  • Maven安装与配置详解、多镜像节点的配置

    下载 Maven是Apache下面的一个项目 xff0c 官网下载地址 xff1a https maven apache org download cgi 历史版本下载地址 xff1a https archive apache org di
  • 使用FTPClient上传文件到ftp服务器。并解决图片损坏问题。

    1 先借鉴此博客的方法 xff08 此博客的方法上传txt文件没有问题 xff0c 但是上传的图片文件会损坏 xff09 https blog csdn net weixin 37196194 article details 5500166
  • libnet的使用详解

    最近搬砖需要对libnet进行介绍在这里对知识进行汇总 1 libnet简介 在 libnet 出现以前 xff0c 如果要构造数据包并发送到网络中 xff0c 程序员要通过一些复杂的接口来处理 libnet 的出现 xff0c 为程序员提
  • electron启动报错

    一个简单的程序启动居然报错了 xff0c 那就排查原因吧 xff0c 搜索网上的资料没有一个一样的 xff0c 大致类似的说的是electron版本和node不一致 还有说是electron的版本问题 但排查后都不是 xff0c 最后我把m
  • 手把手使用 Egg+TypeScript+mongoDB快速实现增删改查

    创建一个Egg的TS项目 xff08 Egg js官方教程 xff09 安装MogoDB Egg 依赖 span class token function npm span span class token function install
  • 小白学java——做一个歌手比赛系统(一)

    xfeff xfeff 完整代码加实验报告都在https download csdn net download qq 39980334 11232331 我已经设置成0积分下载了 xff0c 有需要的自行下载 xff0c 有问题的多看看代码
  • 使用尾插法创建链表并打印输出

    include lt stdio h gt include lt stdlib h gt include lt string h gt typedef struct LNode struct LNode next int data LNod
  • RabbitMQ 发展史与安装

    RabbitMQ 天降奇兵 解决的实例1 xff1a 统计用户的行为 xff0c 利用消息队列解耦模块和认证服务器 xff0c 认证模块被设计为 xff0c 在每一次请求页面的时候 xff0c 发送一条认证请求消息到rabbitmq xff
  • 小白学java------做一个歌手比赛系统(二)

    完整代码加实验报告都在 https download csdn net download qq 39980334 11232331 我已经设置成0积分下载了 xff0c 有需要的自行下载 xff0c 如果页面打不开可能还在审核中 xff08
  • 网络爬虫入门

    1 网络爬虫 网络爬虫 xff08 Web crawler xff09 xff0c 是一种按照一定的规则 xff0c 自动地抓取万维网信息的程序或者脚本 1 1 爬虫入门程序 1 1 1 环境准备 JDK1 8IntelliJ IDEAID
  • Java API入门篇

    文章目录 1 API1 1 API概述1 2 如何使用API帮助文档 2 String类2 1 String类概述2 2 String类的特点2 3 String类的构造方法2 4 创建字符串对象两种方式的区别2 5 字符串的比较2 5 1
  • Java异常篇

    文章目录 1 异常2 JVM默认处理异常的方式3 try catch方式处理异常4 Throwable成员方法5 编译时异常和运行时异常的区别6 throws方式处理异常7 throws和throw的区别8 自定义异常 1 异常 异常的概述
  • Java集合篇

    文章目录 1 Collection集合1 1 集合体系结构1 2 Collection集合概述和基本使用1 3 Collection集合的常用方法1 4 Collection集合的遍历1 5 集合使用步骤图解1 6 集合的案例 Collec