Review: Java SE 03(常用类、String类、可变字符串类和日期类、集合类库)


Java SE 03

目录
  • Java SE 03
    • 一、常用类的概述和使用
      • 1. 常用的包
      • 2. Object类的概述
      • 3. 包装类(Wrapper)
      • 4. 数学处理类
    • 二、String类概述和使用
      • 1. String类的概念
      • 2. 常量池的概念
      • 3. String类的常用构造方法
      • 4. 常用的成员方法
      • 5. 正则表达式
    • 三、可变字符串类和日期类
      • 1. 可变字符串类
      • 2. Java8之前的日期相关类
      • 3. Java8中的日期相关类
    • 四、集合类库(一)
      • 1. 集合的概述
      • 2. Collection集合
      • 3. Iterator接口
      • 4. for each循环
      • 5. List集合
      • 6. Queue集合
    • 五、集合类库(二)
      • 1. 泛型机制
      • 2. Set集合
      • 3. Map集合
      • 4. Collections类

一、常用类的概述和使用

1. 常用的包

  • java.lang包 - 该包是Java语言的核心包,并且该包中的所有内容由Java虚拟机自动导入,不用再手动使用import导入。

    如:System类、String类、...

2. Object类的概述

  • 如果定义一个Java类时没有使用extends关键字声明其父类,则其父类为 java.lang.Object 类

    这个类中若使用了super();其实是调用了Object类中的无参构造方法

  • 为满足Java官方的常规协定,hashCode方法与equals方法的结果要保持一致,所以若equals方法被重写后,则应该重写hashCode方法来保证结果的一致性

    //示例Code
    
    //在equals方法中以id和name相等为判断两个这种类的对象是否相等
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
    
        Student student = (Student) o;
    
        if (id != student.id) return false;
        return name != null ? name.equals(student.name) : student.name == null;
    }
    //在hashCode方法中同样依据equals方法中的基准(以id和name这两个成员变量)进行重写
    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }
    
  • Object类中的toString方法,使用print或println打印引用字符串拼接引用(使用+)都会自动调用该方法

3. 包装类(Wrapper)

  • 在Java5发布之前使用包装类对象进行运算时,需要较为繁琐的“拆箱”和“装箱”操作;即运算前先将包装类对象拆分为基本类型数据,运算后再将结果封装成包装类对象。从Java5开始增加了自动拆箱和自动装箱的功能。

  • 自动装箱池:在Integer类的内部提供了自动装箱池技术,将-128到127之间的整数已经装箱完毕,当程序中使用该范围之间的整数时,无需装箱直接取用自动装箱池中的对象即可,从而提高效率

    //从Java5开始增加了自动装箱和自动拆箱的机制
    Integer it5 = 100;  // 直接通过赋值运算符实现自动装箱
    int ib = it5;       // 直接通过赋值运算符实现自动拆箱
    
    System.out.println("------------------------------------------------------");
    //装箱和拆箱的考点
    Integer it6 = 127; //128;
    Integer it7 = 127; //128;
    Integer it8 = new Integer(127); //new Integer(128);
    Integer it9 = new Integer(127); //new Integer(128);
    System.out.println(it6 == it7);      // 比较地址  128false  127true  地址一样
    System.out.println(it6.equals(it7)); // 比较内容  true
    System.out.println(it8 == it9);      // 比较地址  false
    System.out.println(it8.equals(it9)); // 比较内容  true
    
    System.out.println("------------------------------------------------------");
    

    128不在自动装箱池中,所以每次都会创建自动装箱创建新的对象,所以两次装箱后地址不同

    127在自动装箱池中,不会再创建新的对象,使用同一地址的装箱完成的包装类对象

  • 包装类中常用方法:

    1. 手动装箱的几种方法:

      • 直接使用包装类的带参构造方法,一般有两种重载形式,一种是传入基本数据类型如Integer(int value),另一种是传入代表基本数据类型的字符串Integer(String s),不过使用包装类带参构造方法的装箱基本都已过时
      • static Xxx valueOf(xxx x),静态方法
    2. 手动拆箱的几种方法

      • xxx xxxValue():如int intValue()

      • static xxx parseXxx(String s) :静态方法,从传入的字符串中生成包装类并拆箱

        //实现从String类型到boolean类型的转换
        //boolean b3 = Boolean.parseBoolean("112");
        // 该方法的执行原理是:只要参数数值不为true或者TRUE时,则结果就是false,查手册和源码
        boolean b3 = Boolean.parseBoolean("TRUE");
        System.out.println("b3 = " + b3); // true
        
    3. 返回描述调用对象数值的字符串形式

      • String toString()
    4. 比较调用对象与参数指定的对象是否相等

      • boolean equals(Object obj)
  • java.lang.Number类是个抽象类,基本数据类型中除boolean和char其余的包装类都继承自Number, 这些包装类中都要重写Number中的xxxValue方法

4. 数学处理类

  • java.lang.Math类主要用于提供执行数学运算的方法,如:对数,平方根,大多是静态方法

    /**
     * 编程实现对Math类中常用方法的测试
     */
    public class MathTest {
    
        public static void main(String[] args) {
    
            System.out.println("获取两个整数中最大值的结果是:" + Math.max(10, 20)); // 20
            System.out.println("获取两个整数中最小值的结果是:" + Math.min(10, 20)); // 10
            System.out.println("获取次方的结果是:" + Math.pow(2, 3)); // 8.0  体现double类型
            System.out.println("获取绝对值的结果是:" + Math.abs(-5)); // 5
            System.out.println("进行四舍五入的结果是:" + Math.round(3.14)); // 3
            System.out.println("该整数的平方根是:" + Math.sqrt(16)); // 4.0
            System.out.println("生成的随机数是:" + Math.random()); // 返回0.0到1.0的随机数
        }
    }
    
  • 由于float类型和double类型在运算时可能会有误差,若希望实现精确运算则借助java.math.BigDecimal类型加以描述。

    public class BigDecimalTest {
    
        public static void main(String[] args) {
    
            // 1.构造BigDecimal类型的两个对象
            BigDecimal bd1 = new BigDecimal("5.2");
            BigDecimal bd2 = new BigDecimal("1.3");
            // 2.使用构造完毕的对象实现加减乘除运算
            System.out.println("实现加法运算的结果是:" + bd1.add(bd2)); // 6.5
            System.out.println("实现减法运算的结果是:" + bd1.subtract(bd2)); // 3.9
            System.out.println("实现乘法运算的结果是:" + bd1.multiply(bd2)); // 6.76
            System.out.println("实现除法运算的结果是:" + bd1.divide(bd2)); // 4
    
            System.out.println("---------------------------------------------------------------");
            // 3.实现精确运算
            System.out.println(0.1 + 0.2); // 0.30000000000000004
            BigDecimal bd3 = new BigDecimal("0.1");
            BigDecimal bd4 = new BigDecimal("0.2");
            System.out.println("精确计算的结果是:" + bd3.add(bd4)); // 0.3
    
            System.out.println("---------------------------------------------------------------");
            // 4.无限循环小数注意事项:除法运算需要使用重载形式,传入舍入模式的参数
            BigDecimal bd5 = new BigDecimal("2");
            BigDecimal bd6 = new BigDecimal("0.3");
            System.out.println("除法运算的结果是:" + bd5.divide(bd6, RoundingMode.HALF_UP)); // 7(采用四舍五入)
        }
    }
    
  • 若希望表示比long类型范围还大的整数数据,则需要借助java.math.BigInteger类型描述。

    public class BigIntegerTest {
    
        public static void main(String[] args) {
    
            // 1.构造两个BigInteger类型的对象并指定初始值
            BigInteger bi1 = new BigInteger("20");
            BigInteger bi2 = new BigInteger("8");
            // 2.实现加减乘除取余操作并打印
            System.out.println("实现加法运算的结果是:" + bi1.add(bi2)); // 28
            System.out.println("实现减法运算的结果是:" + bi1.subtract(bi2)); // 12
            System.out.println("实现乘法运算的结果是:" + bi1.multiply(bi2)); // 160
            System.out.println("实现除法运算的结果是:" + bi1.divide(bi2)); // 2
            System.out.println("实现取余运算的结果是:" + bi1.remainder(bi2)); // 4
    
            System.out.println("-----------------------------------------------------");
            // 3.一次性得到商和余数
            BigInteger[] arr = bi1.divideAndRemainder(bi2);
            for (int i = 0; i < arr.length; i++) {
                System.out.println("下标为" + i + "的元素是:" + arr[i]); // 2 4
            }
        }
    }
    

二、String类概述和使用

1. String类的概念

  • String类描述的字符串是一个final修饰的byte类型常量数组,这个常量在内存中方法区中,因此可以被共享使用

    String str1 = “abc”; // 其中"abc"这个字符串是个常量不可改变
    //改变str1的指向并没有改变指向的内容
    str1 = “123”; // 将“123”字符串的地址赋值给变量str1
    

    此时"abc"和"123"都在内存方法区中,当"abc"没有引用变量的指向时会被JVM垃圾回收释放这个内存空间

2. 常量池的概念

  • 由于String类型描述的字符串内容是常量不可改变,因此Java虚拟机将首次出现的字符串放入常量池中,若后续代码中出现了相同字符串内容则直接使用池中已有的字符串对象而无需申请内存及创建对象,从而提高了性能。

    public class StringPoolTest {
    
        public static void main(String[] args) {
    
            // 1.验证一下常量池的存在
            // 到目前为止,只有String这个特殊类除了new的方式外还可以直接字符串赋值(包装类除外)
            String str1 = "abc";
            String str2 = "abc";
            System.out.println(str1 == str2); // 比较地址  true
    
        }
    }
    
  • String类型对象两种创建方式的比较

    public class StringExamTest {
    
        public static void main(String[] args) {
    
            // 1.请问下面的代码会创建几个对象?分别存放在什么地方?
            //String str1 = "hello";  // 1个对象  存放在常量池中
            //String str1 = new String("helo"); // 2个对象  1个在常量池中,1个在堆区
    
            // 2.常量池和堆区对象的比较
            String str1 = "hello";  // 常量池
            String str2 = "hello";  // 常量池
            String str3 = new String("hello"); // 堆区
            String str4 = new String("hello"); // 堆区
    
            System.out.println(str1 == str2);       // 比较地址  true
            System.out.println(str1.equals(str2));  // 比较内容  true
            System.out.println(str3 == str4);       // 比较地址  false
            System.out.println(str3.equals(str4));  // 比较内容  true
            System.out.println(str2 == str4);       // 比较地址  false
            System.out.println(str2.equals(str4));  // 比较内容 true
    
            System.out.println("------------------------------------------------------------");
            // 3.常量有优化机制,变量没有
            String str5 = "abcd";
            //常量与常量进行拼接会进行优化,得到与常量池中相同的对象
            String str6 = "ab" + "cd";  // 常量优化机制  "abcd"
            System.out.println(str5 == str6); // 比较地址  true
    
            
            String str7 = "ab";
            //变量与常量进行拼接,内部实现早期版本是创建StringBuilder对象进行实现,得到的对象与常量池中地址不同
            String str8 = str7 + "cd"; // 没有常量优化
            System.out.println(str5 == str8); // 比较地址 false
        }
    }
    

3. String类的常用构造方法

  • 空参构造方法创建空字符串""

    // 1.使用无参方式构造对象并打印
    String str1 = new String();
    // "" 表示空字符串对象,有对象只是里面没有内容
    // null 表示空,连对象都没有
    System.out.println("str1 = " + str1); // ""  自动调用toString方法
    
  • 传入字节数组创建String对象

    // 2.使用参数指定的byte数组来构造对象并打印
    // 'a' - 97
    byte[] bArr = {97, 98, 99, 100, 101};
    // 使用字节数组中的一部分内容来构造对象,表示使用数组bArr中下标从1开始的3个字节构造字符串对象
    // 构造字符串的思路:就是先将每个整数翻译成对应的字符,再将所有的字符串起来。
    // 98 - 'b'   99 - 'c'  100 - 'd'   => bcd
    String str2 = new String(bArr, 1, 3);
    System.out.println("str2 = " + str2); // bcd
    
    // 使用整个字节数组来构造字符串对象
    String str3 = new String(bArr);
    System.out.println("str3 = " + str3); // abcde
    
  • 传入字符数组创建String对象

    // 3.使用字符数组来构造字符串对象
    char[] cArr = {'h', 'e', 'l', 'l', 'o'};
    // 使用字符数组中的一部分内容来构造对象
    // 思路:直接将字符串起来
    String str4 = new String(cArr, 2, 2);
    System.out.println("str4 = " + str4); // ll
    // 使用整个字符数组来构造对象
    String str5 = new String(cArr);
    System.out.println("str5 = " + str5); // hello
    
  • 传入字符串创建String对象

    // 4.使用字符串来构造字符串对象
    String str6 = new String("world");
    System.out.println("str6 = " + str6); // world
    

4. 常用的成员方法

  • 将String对象转换为字符数组字节数组的方法(toCharArray和getBytes)

    public class StringByteCharTest {
    
        public static void main(String[] args) {
    
            // 1.创建String类型的对象并打印
            String str1 = new String("world");
            System.out.println("str1 = " + str1); // world
    
            System.out.println("-----------------------------------------------");
            // 2.实现将String类型转换为byte数组类型并打印
            // 思路:先将字符串拆分为字符,将再每个字符转换为byte类型,也就是获取所有字符的ASCII
            byte[] bArr = str1.getBytes();
            for (int i = 0; i < bArr.length; i++) {
                System.out.println("下标为i的元素是:" + bArr[i]);
            }
            // 将byte数组转回String类型并打印
            String str2 = new String(bArr);
            System.out.println("转回字符串为:" + str2); // world
    
            System.out.println("-----------------------------------------------");
            // 3.实现将String类型转换为char数组类型并打印
            // 思路:将字符串拆分为字符并保存到数组中
            char[] cArr = str1.toCharArray();
            for (int i = 0; i < cArr.length; i++) {
                System.out.println("下标为" + i + "的字符是:" + cArr[i]);
            }
            // 将char数组转回String类型并打印
            String str3 = new String(cArr);
            System.out.println("转回字符串为:" + str3); // world
        }
    }
    
    /*
    str1 = world
    -----------------------------------------------
    下标为i的元素是:119
    下标为i的元素是:111
    下标为i的元素是:114
    下标为i的元素是:108
    下标为i的元素是:100
    转回字符串为:world
    -----------------------------------------------
    下标为0的字符是:w
    下标为1的字符是:o
    下标为2的字符是:r
    下标为3的字符是:l
    下标为4的字符是:d
    转回字符串为:world
    */
    
  • 根据索引返回字符串中的字符的方法(charAt)、获取字符串长度的方法(length)、字符串判空的方法(isEmpty)

    public class StringCharTest {
    
        public static void main(String[] args) {
    
            // 1.构造String类型的对象并打印
            String str1 = new String("hello");
            System.out.println("str1 = " + str1); // hello
            // 2.获取字符串的长度和每个字符并打印
            System.out.println("字符串的长度是:" + str1.length()); // 5
            System.out.println("下标为0的字符是:" + str1.charAt(0)); // h
            System.out.println("下标为1的字符是:" + str1.charAt(1)); // e
            System.out.println("下标为2的字符是:" + str1.charAt(2)); // l
            System.out.println("下标为3的字符是:" + str1.charAt(3)); // l
            System.out.println("下标为4的字符是:" + str1.charAt(4)); // o
            //System.out.println("下标为5的字符是:" + str1.charAt(5)); // StringIndexOutOfBoundsException 字符串下标越界异常
    
            System.out.println("----------------------------------------------");
            // 3.使用for循环获取所有字符
            for (int i = 0; i < str1.length(); i++) {
                System.out.println("下标为" + i + "的字符是:" + str1.charAt(i)); // h e l l o
            }
    
            System.out.println("----------------------------------------------");
            // 4.判断字符串是否为空
            System.out.println(0 == str1.length()? "字符串为空": "字符串不为空"); // 不为空
            System.out.println(str1.isEmpty()? "字符串为空": "字符串不为空");     // 不为空
    
            System.out.println("----------------------------------------------");
            // 5.笔试考点
            // 使用两种方式实现字符串"12345"转换为整数12345并打印
            String str2 = new String("12345");
            // 方式一:调用Integer类中的parseInt()方法即可
            int ia = Integer.parseInt(str2);
            System.out.println("转换出来的整数是:" + ia); // 12345
            // 方式二:利用ASCII来实现类型转换并打印
            // '1' - '0' => 1  '2' - '0' => 2  ...
            int ib = 0;
            for (int i = 0; i < str2.length(); i++) {
                ib = ib*10 + (str2.charAt(i) - '0'); // 1 12 ...
            }
            System.out.println("转换出来的结果是:" + ib); // 12345
    
            System.out.println("----------------------------------------------");
            // 如何实现整数到字符串的转换
            //String str3 = String.valueOf(ib);
            String str3 = "" + ib; // 推荐使用
            System.out.println("str3 = " + str3); // 12345
        }
    }
    

    案例:字符串回文判断

    public class StringJudgeTest {
    
        public static void main(String[] args) {
    
            // 1.创建字符串对象并打印
            String str1 = new String("上海自来水来自海上");
            System.out.println("str1 = " + str1); // 上海自来水来自海上   9
            // 2.判断该字符串内容是否为回文并打印
            for (int i = 0; i < str1.length()/2; i++) {
                if (str1.charAt(i) != str1.charAt(str1.length()-i-1)) {  // 0和8   1和7  2和6  3和5
                    System.out.println(str1 + "不是回文!");
                    return;  // 仅仅是用于实现方法的结束
                }
            }
            System.out.println(str1 + "是回文!");
        }
    }
    
  • 与传入的字符串比较大小的方法(compareTo和compareToIgnoreCase)

    public class StringCompareTest {
    
        public static void main(String[] args) {
    
            // 1.构造String类型的对象并打印
            String str1 = new String("hello");
            System.out.println("str1 = " + str1); // hello
    
            // 2.使用构造好的对象与其它字符串对象之间比较大小并打印
            System.out.println(str1.compareTo("world"));  // 'h' - 'w' => 104 - 119 => -15
            System.out.println(str1.compareTo("haha"));   // 'e' - 'a' => 101 - 97  => 4
            System.out.println(str1.compareTo("hehe"));   // 'l' - 'h' => 108 - 104 => 4
            System.out.println(str1.compareTo("heihei")); // 'l' - 'i' => 108 - 105 => 3
            System.out.println(str1.compareTo("helloworld")); // 根据长度比较: 5 - 10 => -5
            System.out.println(str1.compareToIgnoreCase("HELLO")); // 0
        }
    }
    /*
    str1 = hello
    -15
    4
    4
    3
    -5
    0
    */
    
  • 检测是否包含子串的方法(contains)、转换大小写的方法、判断字符串是否以一个字串作为开头或结尾的方法

    public class StringManyMethodTest {
    
        public static void main(String[] args) {
    
            // 1.构造String类型的对象并打印
            String str1 = new String("     Let Me Give You Some Color To See See!");
            System.out.println("str1 = " + str1); //      Let Me Give You Some Color To See See!
    
            // 2.实现各种成员方法的调用和测试
            boolean b1 = str1.contains("some");
            System.out.println("b1 = " + b1); // false  区分大小写
            b1 = str1.contains("Some");
            System.out.println("b1 = " + b1); // true
    
            System.out.println("----------------------------------------------");
            // 将所有字符串转换为大写  小写  以及去除两边的空白字符
            String str2 = str1.toUpperCase();
            System.out.println("str2 = " + str2); //    LET ME GIVE YOU SOME COLOR TO SEE SEE!
            System.out.println("str1 = " + str1); //    Let Me Give You Some Color To See See!   常量
    
            String str3 = str1.toLowerCase();
            System.out.println("str3 = " + str3); //    let me give you some color to see see!
            System.out.println("str1 = " + str1); //    Let Me Give You Some Color To See See!
    
            String str4 = str1.trim();
            System.out.println("str4 = " + str4); //Let Me Give You Some Color To See See!     奇点
    
            System.out.println("----------------------------------------------");
            // 判断字符串是否以...开头  以...结尾
            b1 = str1.startsWith("Let");
            System.out.println("b1 = " + b1); // false
            b1 = str1.startsWith(" ");
            System.out.println("b1 = " + b1); // true
            // 从下标5开始是否以"Let"开头
            b1 = str1.startsWith("Let", 5);
            System.out.println("b1 = " + b1); // true
    
            b1 = str1.endsWith("See");
            System.out.println("b1 = " + b1); // false
            b1 = str1.endsWith("See!");
            System.out.println("b1 = " + b1); // true
        }
    }
    
  • 比较当前字符串是否与传入的字符串内容相同的方法(equals和equalsIgnoreCase)

    /*
    提示用户从键盘输入用户名和密码信息,若输入”admin”和”123456”则提示“登录成功,欢迎使用”,否则提示“用户名或密码错误,您还有n次机会”,若用户输入三次后依然错误则提示“账户已冻结,请联系客服人员!”
    */
    public class StringEqualsTest {
    
        public static void main(String[] args) {
    
            Scanner sc = new Scanner(System.in);
            for (int i = 3; i > 0; i--) {
                // 1.提示用户从键盘输入用户名和密码信息并使用变量记录
                System.out.println("请输入您的用户名和密码信息:");
                String userName = sc.next();
                String password = sc.next();
    
                // 2.判断用户名和密码是否为"admin"和"123456"并给出提示
                //if ("admin".equals(userName) && "123456".equals(password)) {
                if ("admin".equalsIgnoreCase(userName) && "123456".equals(password)) { // 防止空指针异常
                    System.out.println("登录成功,欢迎使用!");
                    break;
                } //else {
                if (1 == i) {
                    System.out.println("账户已冻结,请联系客服人员!");
                } else {
                    System.out.println("用户名或密码错误,您还有" + (i - 1) + "次机会!");
                }
                //}
            }
            // 关闭扫描器
            sc.close();
        }
    }
    
  • 获取指定字符或字符串在当前字符串中的索引的方法(indexOf和lastIndexOf)

    public static void main(String[] args) {
    
        // 1.构造String类型的对象并打印
        String str1 = new String("Good Good Study, Day Day Up!");
        System.out.println("str1 = " + str1); // Good Good Study, Day Day Up!
    
        // 2.实现字符串中指定字符和字符串的查找功能
        int pos = str1.indexOf('g');
        System.out.println("pos = " + pos); // -1  代表查找失败
        pos = str1.indexOf('G');
        System.out.println("pos = " + pos); // 0   该字符第一次出现的索引位置
        // 表示从下标0开始查找字符'G'第一次出现的索引位置,包含0
        pos = str1.indexOf('G', 0);
        System.out.println("pos = " + pos); // 0
        pos = str1.indexOf('G', 1);
        System.out.println("pos = " + pos); // 5
    
        System.out.println("------------------------------------------------------");
        // 查找字符串
        pos = str1.indexOf("day");
        System.out.println("pos = " + pos); // -1
        pos = str1.indexOf("Day");
        System.out.println("pos = " + pos); // 17   字符串中第一个字符的下标
        pos = str1.indexOf("Day", 17);
        System.out.println("pos = " + pos); // 17   字符串中第一个字符的下标
        pos = str1.indexOf("Day", 18);
        System.out.println("pos = " + pos); // 21   字符串中第一个字符的下标
    
        System.out.println("------------------------------------------------------");
        // 3.实现字符和字符串内容的反向查找
        pos = str1.lastIndexOf('G');
        System.out.println("pos = " + pos); // 5
        // 从下标5的位置开始反向查找
        pos = str1.lastIndexOf('G', 5);
        System.out.println("pos = " + pos); // 5
    
        pos = str1.lastIndexOf('G', 6);
        System.out.println("pos = " + pos); // 5
    
        pos = str1.lastIndexOf('G', 4);
        System.out.println("pos = " + pos); // 0
    
        System.out.println("------------------------------------------------------");
        pos = str1.lastIndexOf("Day");
        System.out.println("pos = " + pos); // 21
        pos = str1.lastIndexOf("Day",  21);
        System.out.println("pos = " + pos); // 21
        pos = str1.lastIndexOf("Day", 20);
        System.out.println("pos = " + pos); // 17
        pos = str1.lastIndexOf("Day", 15);
        System.out.println("pos = " + pos); // -1
    }
    

    案例:查找指定子串在字符串中出现的所有索引

    // 编写通用代码实现将字符串str1中所有"Day"出现的索引位置找到并打印出来
    String str1 = new String("Good Good Study, Day Day Up!");
    System.out.println("str1 = " + str1); // Good Good Study, Day Day Up!
    
    pos = str1.indexOf("Day");
    while (-1 != pos) {
        System.out.println("pos = " + pos); // 17
        pos = str1.indexOf("Day", pos+1);
    }
    
    System.out.println("------------------------------------------------------");
    // 优化一下
    pos = 0;
    while ((pos = str1.indexOf("Day", pos)) != -1) {
        System.out.println("pos = " + pos);
        pos += "Day".length();
    }
    
  • 从指定的索引中获取子串的方法(substring)

    public class SubStringTest {
    
        public static void main(String[] args) {
    
            // 1.构造String类型的对象并打印
            String str1 = new String("Happy Wife, Happy Life!");
            System.out.println("str1 = " + str1); // Happy Wife, Happy Life!
    
            // 2.获取字符串中的一部分内容并打印
            // 表示从当前字符串中下标12开始获取子字符串
            String str2 = str1.substring(12);
            System.out.println("str2 = " + str2); // Happy Life!
            // 可以取到6但是取不到10
            String str3 = str1.substring(6, 10);
            System.out.println("str3 = " + str3); // Wife
    
            System.out.println("---------------------------------------------------------");
        }
    }
    

    案例:提示用户从键盘输入一个字符串和一个字符,输出该字符(不含)后面的所有子字符串

    // 3.获取输入字符串中从输入字符起的子字符串内容
    System.out.println("请输入一个字符串:");
    Scanner sc = new Scanner(System.in);
    String str4 = sc.next();
    System.out.println("请输入一个字符:");
    String str5 = sc.next();
    // 从str4中查找str5第一次出现的索引位置
    int pos = str4.indexOf(str5);
    System.out.println("pos = " + pos);
    // 根据该位置获取子字符串
    String str6 = str4.substring(pos+1);
    System.out.println("获取到的子字符串是:" + str6);
    
  • 静态方法:将基本数据类型转换为String类型的对象(String.valueOf(xxx))

    // 如何实现整数到字符串的转换
    int ib = 12345;
    //String str3 = String.valueOf(ib);
    String str3 = "" + ib; // 推荐使用
    System.out.println("str3 = " + str3); // 12345
    

5. 正则表达式

  • 正则表达式相关的方法:判断当前正在调用的字符串是否匹配参数指定的正则表达式规则boolean matches(String regex)

    案例:根据需求实现对数据格式的验证

    public class StringRegTest {
    
        public static void main(String[] args) {
    
            // 1.定义描述规则的正则表达式字符串并使用变量记录
            // 正则表达式只能对数据格式进行验证,无法对数据内容的正确性进行检查,内容的正确性检查需要后台查询数据库
            // 描述银行卡密码的规则:由6位数字组成
            //String reg = "^[0-9]{6}$";
            //String reg = "[0-9]{6}";
            //String reg = "\\d{6}";
            // 使用正则表达式描述一下QQ号码的规则:要求是由非0开头的5~15位数字组成。
            //String reg = "[1-9]\\d{4,14}";
            //使用正则表达式描述一下手机号码的规则:要求是由1开头,第二位数是3、4、5、7、8中的一位,总共11位
            //String reg = "1[34578]\\d{9}";
            //描述身份证号码的规则:总共18位,6位数字代表地区,4位数字代表年,2位数字代表月,2位数字代表日期, 3位数字代表个人,
            // 最后一位可能数字也可能是X。
            String reg = "(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9|X])";
            // 2.提示用户从键盘输入指定的内容并使用变量记录
            Scanner sc = new Scanner(System.in);
            while(true) {
                //System.out.println("请输入您的银行卡密码:");
                //System.out.println("请输入您的QQ号码:");
                //System.out.println("请输入您的手机号码:");
                System.out.println("请输入您的身份证号码:");
                String str = sc.next();
    
                // 3.判断用户输入的字符串内容是否满足指定的规则并打印
                if (str.matches(reg)) {
                    //System.out.println("银行卡密码的格式正确!");
                    System.out.println("输入字符串的格式正确!");
                    break;
                } else {
                    //System.out.println("银行卡密码的格式错误!");
                    System.out.println("输入字符串的格式错误!");
                }
            }
        }
    }
    
  • 正则表达式与操作字符串相关的方法

    • 使用正则表达式参数的规则所表示的字符串为分隔符进行字符串切割

      String[] split(String regex)

    • 使用正则表达式参数的规则进行字符串替换

      String replace(char oldChar, char newChar)

      String replaceFirst(String regex, String replacement)

      String replaceAll(String regex, String replacement)

    • 示例Code

      public static void main(String[] args) {
      
          // 1.准备一个字符串对象并打印
          String str1 = "1001,zhangfei,30";
          System.out.println("str1 = " + str1); // 1001,zhangfei,30
          // 2.按照逗号对字符串内容进行切割
          String[] sArr = str1.split(",");
          for (int i = 0; i < sArr.length; i++) {
              System.out.println("下标为" + i + "的字符串是:" + sArr[i]); // 1001 zhangfei 30
          }
      
          System.out.println("--------------------------------------------------------------");
          // 3.准备一个字符串内容并进行替换
          String str2 = "我的小名叫大帅哥";
          // 将字符串中所有的字符'我'替换为'你'
          String str3 = str2.replace('我', '你');
          System.out.println("str2 = " + str2); // 我的小名叫大帅哥
          System.out.println("str3 = " + str3); // 你的小名叫大帅哥
          // 将字符串中所有的字符'大'替换为'小'
          String str4 = str3.replace('大', '小');
          System.out.println("str4 = " + str4); // 你的小名叫小帅哥
          // 将字符串中所有的字符'小'替换为'大'
          String str5 = str4.replace('小', '大');
          System.out.println("str5 = " + str5); // 你的大名叫大帅哥
      
          System.out.println("--------------------------------------------------------------");
          // 4.准备一个字符串进行字符串内容的替换
          String str6 = "123abc456def789ghi";
          // 将第一个数字字符串替换为"#"
          String str7 = str6.replaceFirst("\\d+", "#");
          System.out.println("替换第一个字符串后的结果是:" + str7); // #abc456def789ghi
          // 将所有字母字符串替换为"$$$"
          String str8 = str7.replaceAll("[a-z]+", "A");
          System.out.println("str8 = " + str8); // #A456A789A
      
      }
      

三、可变字符串类和日期类

1. 可变字符串类

  • StringBuilder的构造方法

    // 1.使用无参方式构造StringBuilder类型的对象并打印容量和长度
    StringBuilder sb1 = new StringBuilder();
    System.out.println("sb1 = " + sb1); // 自动调用toString方法 啥也没有
    System.out.println("容量是:" + sb1.capacity()); // 16
    System.out.println("长度是:" + sb1.length()); // 0
    
    System.out.println("-----------------------------------------------------------");
    // 2.使用参数指定的容量来构造对象并打印容量和长度
    StringBuilder sb2 = new StringBuilder(20);
    System.out.println("sb2 = " + sb2); // 自动调用toString方法 啥也没有
    System.out.println("容量是:" + sb2.capacity()); // 20
    System.out.println("长度是:" + sb2.length()); // 0
    
    System.out.println("-----------------------------------------------------------");
    // 3.根据参数指定的字符串内容来构造对象并打印容量和长度
    StringBuilder sb3 = new StringBuilder("hello");
    System.out.println("sb3 = " + sb3); // 自动调用toString方法  hello
    System.out.println("容量是:" + sb3.capacity()); // 16 + 5 = 21
    System.out.println("长度是:" + sb3.length()); // 5
    
    System.out.println("-----------------------------------------------------------");
    String str1 = new String("hello");
    String str2 = str1.toUpperCase();
    System.out.println("str2 = " + str2); // HELLO
    System.out.println("str1 = " + str1); // hello  字符串本身是个常量不会改变
    
  • 操作StringBuilder对象的相关方法

    // 4.实现向字符串中插入和追加字符串内容
    // 向下标为0的位置插入字符串内容"abcd",也就是向开头位置插入字符串内容
    StringBuilder sb4 = sb3.insert(0, "abcd");
    System.out.println("sb4 = " + sb4); // abcdhello  返回调用对象自己的引用,也就是返回值和调用对象是同一个字符串
    System.out.println("sb3 = " + sb3); // abcdhello
    // 向中间位置插入字符串"1234"
    sb3.insert(4, "1234");
    System.out.println("sb3 = " + sb3); // abcd1234hello
    // 向末尾位置插入字符串"ABCD"
    sb3.insert(sb3.length(), "ABCD");
    System.out.println("sb3 = " + sb3); // abcd1234helloABCD
    
    System.out.println("-----------------------------------------------------------");
    // 向末尾位置追加字符串内容
    sb3.append("world");
    System.out.println("sb3 = " + sb3); // abcd1234helloABCDworld
    // 当字符串的长度超过了字符串对象的初始容量时,该字符串对象会自动扩容,默认扩容算法是:原始容量*2 + 2 => 21*2 + 2 => 44
    // 底层采用byte数组来存放所有的字符内容。
    // ctrl+alt+左右方向键  表示回到上/下一个位置
    System.out.println("容量是:" + sb3.capacity()); // 44
    System.out.println("长度是:" + sb3.length()); // 22
    
    System.out.println("-----------------------------------------------------------");
    // 5.实现字符串中字符和字符串的删除
    // 表示删除下标为8的单个字符
    sb3.deleteCharAt(8);
    System.out.println("sb3 = " + sb3); // abcd1234elloABCDworld
    // 使用for循环删除多个字符
    for (int i = 8; i < 12; i++) {
        // 由结果可知:删除一个字符后就跳过一个字符继续删除,因为每当删除一个字符后后面的字符会向前补位,因为下标会发生变化
        //sb3.deleteCharAt(i);
        // 始终删除下标为8的字符
        sb3.deleteCharAt(8);
    }
    System.out.println("删除后的字符串是:" + sb3); // abcd1234ABCDworld
    
    System.out.println("-----------------------------------------------------------");
    // 删除起始字符串abcd,包含0但不包含4
    sb3.delete(0, 4);
    System.out.println("sb3 = " + sb3); // 1234ABCDworld
    // 删除中间字符串
    sb3.delete(4, 8);
    System.out.println("sb3 = " + sb3); // 1234world
    // 删除末尾字符串
    sb3.delete(4, sb3.length());
    System.out.println("sb3 = " + sb3); // 1234
    
    System.out.println("-----------------------------------------------------------");
    // 6.实现字符串内容的修改、查找以及反转操作
    // 表示将下标为0这个位置的字符修改为'a'
    sb3.setCharAt(0, 'a');
    System.out.println("修改单个字符后的内容是:" + sb3); // a234
    // 修改"234"为"bcd"
    sb3.replace(1, 4, "bcd");
    System.out.println("修改字符串后的结果是:" + sb3); // abcd
    // 实现查找的功能
    int pos = sb3.indexOf("b");
    System.out.println("从前向后查找的结果是:" + pos); // 1
    pos = sb3.lastIndexOf("b");
    System.out.println("从后向前查找的结果是:" + pos); // 1
    // 实现字符串的反转功能
    sb3.reverse();
    System.out.println("反转后的结果是:" + sb3); // dcba
    
    System.out.println("-----------------------------------------------------------");
    // 7.笔试考点
    // 考点一:既然StringBuilder类的对象本身可以修改,那么为什么成员方法还有返回值呢?
    // 解析:为了连续调用
    //sb3.reverse().append("1").append("2").insert(0, "3").delete(0, 1).reverse();
    // 考点二:如何实现StringBuilder类型和String类型之间的转换呢?
    //String str3 = sb3.toString();
    //StringBuilder sb5 = new StringBuilder(str3);
    // 考点三:String、StringBuilder、StringBuffer之间效率谁高?排列如何?
    // String < StringBuffer < StringBuilder
    

2. Java8之前的日期相关类

  • java.lang.System类中的时间相关的静态方法(currentTimeMillis)

    public class SystemTest {
        
        public static void main(String[] args) {
            
            // 1.获取当前系统时间距离1970年1月1日0时0分0秒的毫秒数
            long msec = System.currentTimeMillis();
            System.out.println("当前系统时间距离1970年1月1日0时0分0秒已经过去" + msec + "毫秒了!");
    
            // 通常用于测试某一段代码的执行效率
        }
    }
    /*
    当前系统时间距离1970年1月1日0时0分0秒已经过去1634805953961毫秒了!
    */
    
  • java.util.Date类中描述时间(年月日时分秒)相关的方法

    public class DateTest {
    
        public static void main(String[] args) {
    
            // 1.使用无参方式构造Date对象并打印
            Date d1 = new Date();
            System.out.println("d1 = " + d1); // 获取当前系统时间
    
            System.out.println("------------------------------------");
            // 2.使用参数指定的毫秒数来构造Date对象并打印  1秒 = 1000毫秒  东八区
            Date d2 = new Date(1000);
            System.out.println("d2 = " + d2); // 1970 1 1 8 0 1
    
            System.out.println("------------------------------------");
            // 3.获取调用对象距离1970年1月1日0时0分0秒的毫秒数
            long msec = d2.getTime();
            System.out.println("获取到的毫秒数是:" + msec); // 1000
    
            // 4.设置调用对象所表示的时间点为参数指定的毫秒数
            d2.setTime(2000);
            System.out.println("修改后的时间是:" + d2); // 1970 1 1 8 0 2
        }
    }
    /*
    d1 = Thu Oct 21 16:43:22 CST 2021
    ------------------------------------
    d2 = Thu Jan 01 08:00:01 CST 1970
    ------------------------------------
    获取到的毫秒数是:1000
    修改后的时间是:Thu Jan 01 08:00:02 CST 1970
    */
    
  • java.text.SimpleDateFormat类中实现日期和文本之间转换的方法

    public class SimpleDateFormatTest {
    
        public static void main(String[] args) throws Exception {
    
            // 1.获取当前系统时间并打印
            Date d1 = new Date();
            System.out.println("d1 = " + d1);
    
            // 2.构造SimpleDateFormat类型的对象并指定格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 3.实现日期类型向文本类型的转换并打印
            // alt+Enter 可以实现返回值的生成
            String format = sdf.format(d1);
            System.out.println("转换后的日期为:" + format);
            // 4.实现文本类型到日期类型的转换并打印
            Date parse = sdf.parse(format);
            System.out.println("转回日期格式的结果为:" + parse);
        }
    }
    /*
    d1 = Thu Oct 21 16:48:19 CST 2021
    转换后的日期为:2021-10-21 16:48:19
    转回日期格式的结果为:Thu Oct 21 16:48:19 CST 2021
    */
    
  • java.util.Calendar类用于取代Date类中的过时方法,Calendar中的方法:实现转换成Date类、设置日期中字段值、增加指定字段值

    Calendar类是个抽象类,因此不能实例化对象,其具体子类针对不同国家的日历系统,其中应用最广泛的是GregorianCalendar(格里高利历),对应世界上绝大多数国家/地区使用的标准日历系统。

    public static void main(String[] args) {
    
        // 1.使用过时的方法按照指定的年月日时间分来构造对象,其中年和月的传参按照源码规则分别减去1900和1
        Date d1 = new Date(2008-1900, 8-1, 8, 20, 8, 8);
        // 2.设置日期对象的格式并打印
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(d1);
        System.out.println("获取到的时间是:" + format); // 2008 8 8 20 8 8
    
        System.out.println("-----------------------------------------------------");
        // 2.使用取代的方式按照指定的年月日时分秒来构造对象
        // 2.1 获取Calendar类型的引用
        // 考点:既然Calendar是个抽象类不能创建对象,那么下面的方法为啥可以获取Calendar类型的引用呢?
        // 解析:由源码可知,返回的并不是Calendar类型的对象,而是Calendar类的子类GregorianCalendar等对象,形成了多态
        // 多态的使用场合之三
        /*
        通过方法的返回值类型形成多态
    	Calender getInstance(){
     		return new GregorianCalendar(zone, aLocale);
     	}
     	*/
        Calendar instance = Calendar.getInstance();
        // 2.2 设置指定的年月日时分秒信息,其中月的传参按照源码规则减去1
        instance.set(2008, 8-1, 8, 20, 8, 8);
        // 2.3 转换为Date类型的对象
        Date d2 = instance.getTime();
        String format1 = sdf.format(d2);
        System.out.println("获取到的时间是:" + format1); // 2008 8 8 20 8 8
    
        System.out.println("-----------------------------------------------------");
        // 3.向指定的字段设置以及增加指定的数值
        instance.set(Calendar.YEAR, 2018);
        // 转换为Date类型并按照指定的格式打印
        Date d3 = instance.getTime();
        System.out.println("设置年份后的结果是:" + sdf.format(d3)); // 2018 8 8 20 8 8
    
        instance.add(Calendar.MONTH, 2);
        Date d4 = instance.getTime();
        System.out.println("增加月份后的结果是:" + sdf.format(d4)); // 2018 10 8 20 8 8
    }
    

3. Java8中的日期相关类

  • java.time包:该包是日期/时间API的基础包,

    java.time包解决了java.util.Date和java.util.Calendar面临的问题:

    Date类中的年份是从1900开始的,而月份都从0开始;

    格式化只对Date类有用,对Calendar类则不能使用;

    非线程安全等

    java.time包下常用的类LocalDate、LocalTime、LocalDateTime

    public static void main(String[] args) {
    
        // 1.获取当前日期信息并打印
        LocalDate now = LocalDate.now();
        System.out.println("获取到的当前日期是:" + now);
        // 2.获取当前时间信息并打印
        LocalTime now1 = LocalTime.now();
        System.out.println("获取到的当前时间是:" + now1);
        // 3.获取当前日期时间信息并打印,使用最多
        LocalDateTime now2 = LocalDateTime.now();
        System.out.println("获取到的当前日期时间是:" + now2);
    
        System.out.println("-------------------------------------------------------");
        // 4.使用参数指定的年月日时分秒信息来获取对象并打印
        // 使用ctrl+F12来查找指定的方法
        LocalDateTime of = LocalDateTime.of(2008, 8, 8, 20, 8, 8);
        System.out.println("指定的日期时间是:" + of); // 自动调用toString方法
        System.out.println("获取到的年是:" + of.getYear()); // 2008
        System.out.println("获取到的月是:" + of.getMonthValue()); // 8
        System.out.println("获取到的日是:" + of.getDayOfMonth()); // 8
        System.out.println("获取到的时是:" + of.getHour()); // 20
        System.out.println("获取到的分是:" + of.getMinute()); // 8
        System.out.println("获取到的秒是:" + of.getSecond()); // 8
    
        System.out.println("-------------------------------------------------------");
        // 5.实现特征的设置并打印
        // 与String类型相似,调用对象本身的数据内容不会改变,返回值相当于创建了一个新的对象,由此证明了不可变性
        LocalDateTime localDateTime = of.withYear(2012);
        System.out.println("localDateTime = " + localDateTime); // 2012-08-08T20:08:08
        System.out.println("of = " + of); // 2008-08-08T20:08:08
        LocalDateTime localDateTime1 = localDateTime.withMonth(12);
        System.out.println("localDateTime1 = " + localDateTime1); // 2012 12 8 20 8 8
    
        System.out.println("-------------------------------------------------------");
        // 6.实现特征的增加并打印
        LocalDateTime localDateTime2 = localDateTime1.plusDays(2);
        System.out.println("localDateTime2 = " + localDateTime2); // 2012 12 10 20 8 8
        System.out.println("localDateTime1 = " + localDateTime1); // 2012 12 8 20 8 8
        LocalDateTime localDateTime3 = localDateTime2.plusHours(3);
        System.out.println("localDateTime3 = " + localDateTime3); // 2012 12 10 23 8 8
    
        System.out.println("-------------------------------------------------------");
        // 7.实现特征的减少并打印
        LocalDateTime localDateTime4 = localDateTime3.minusMinutes(1);
        System.out.println("localDateTime4 = " + localDateTime4); // 2012 12 10 23 7 8
        System.out.println("localDateTime3 = " + localDateTime3); // 2012 12 10 23 8 8
        LocalDateTime localDateTime5 = localDateTime4.minusSeconds(3);
        System.out.println("localDateTime5 = " + localDateTime5); // 2012 12 10 23 7 5
    
    }
    /*
    获取到的当前日期是:2021-10-21
    获取到的当前时间是:21:13:13.430616500
    获取到的当前日期时间是:2021-10-21T21:13:13.430616500
    -------------------------------------------------------
    指定的日期时间是:2008-08-08T20:08:08
    获取到的年是:2008
    获取到的月是:8
    获取到的日是:8
    获取到的时是:20
    获取到的分是:8
    获取到的秒是:8
    -------------------------------------------------------
    localDateTime = 2012-08-08T20:08:08
    of = 2008-08-08T20:08:08
    localDateTime1 = 2012-12-08T20:08:08
    -------------------------------------------------------
    localDateTime2 = 2012-12-10T20:08:08
    localDateTime1 = 2012-12-08T20:08:08
    localDateTime3 = 2012-12-10T23:08:08
    -------------------------------------------------------
    localDateTime4 = 2012-12-10T23:07:08
    localDateTime3 = 2012-12-10T23:08:08
    localDateTime5 = 2012-12-10T23:07:05
    */
    
  • java.time.Instant类主要用于描述瞬间的时间点信息,使用方法类似于Date类

    public static void main(String[] args) {
    
        // 1.使用Instant类来获取当前系统时间  并不是当前系统的默认时区  本初子午线   差8小时  东八区
        Instant now = Instant.now();
        System.out.println("获取到的当前时间为:" + now);
    
        // 2.加上时区所差的8个小时
        OffsetDateTime offsetDateTime = now.atOffset(ZoneOffset.ofHours(8));
        System.out.println("偏移后的日期时间为:" + offsetDateTime);
    
        System.out.println("--------------------------------------------------------");
        // 3.获取当前调用对象距离标准基准时间的毫秒数
        long g1 = now.toEpochMilli();
        System.out.println("获取到的毫秒差为:" + g1);
    
        // 4.根据参数指定的毫秒数来构造对象
        Instant instant = Instant.ofEpochMilli(g1);
        System.out.println("根据参数指定的毫秒数构造出来的对象为:" + instant);
    }
    /*
    获取到的当前时间为:2021-10-21T14:05:04.385320Z
    偏移后的日期时间为:2021-10-21T22:05:04.385320+08:00
    --------------------------------------------------------
    获取到的毫秒差为:1634825104385
    根据参数指定的毫秒数构造出来的对象为:2021-10-21T14:05:04.385Z
    */
    
  • java.time.format.DateTimeFormatter类主要用于格式化和解析日期,使用方法类似于SimpleDateFormat类

    String format(TemporalAccessor temporal) 将参数指定日期时间转换为字符串

    TemporalAccessor是接口,实现类有Instant、LocalTime、LocalDate、LocalDateTime等

    public class DateTimeFormatterTest {
    
        public static void main(String[] args) {
    
            // 1.获取当前系统的日期时间并打印
            LocalDateTime now = LocalDateTime.now();
            System.out.println("now = " + now);
    
            // 2.按照指定的格式准备一个DateTimeFormatter类型的对象
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 3.实现日期时间向字符串类型的转换并打印
            String str = dateTimeFormatter.format(now);
            System.out.println("调整格式后的结果是:" + str);
            // 4.实现字符串类型到日期时间类型的转换并打印
            TemporalAccessor parse = dateTimeFormatter.parse(str);
            System.out.println("转回去的结果是:" + parse);
        }
    }
    

四、集合类库(一)

1. 集合的概述

  • 当需要在Java程序中记录多个类型不同的数据内容时,则创建一个对象(类中可以定义不同类型的成员变量,创建对象可以存储多个不同类型的数据,数组只能解决存储多个类型相同的数据);当需要在Java程序中记录多个类型不同的对象数据时,则准备一个集合(对象数组只能解决存储多个类型相同的对象)

  • Java中集合框架顶层框架是:java.util.Collection集合 和 java.util.Map集合

    Collection集合中存取元素的基本单位是:单个元素,Map集合中存取元素的基本单位是:一对元素

2. Collection集合

  • Collection接口与List接口、Queue接口、Set接口是父子接口继承关系,Collection接口的方法可以被子接口继承

  • Collection接口常用方法

    • Collection接口中add方法与addAll方法

      add方法添加集合元素时将整个集合添加,addAll方法添加元素将集合中元素按个依次添加

      // 1.准备一个Collection集合并打印
      //Collection c1 = new Collection();  // 接口不能实例化,也就是不能创建对象
      // 接口类型的引用指向实现类的对象,形成了多态
      Collection c1 = new ArrayList();
      // 自动调用toString方法,调用ArrayList类中的toString方法,默认打印格式为:[元素值1, 元素值2, ...]
      System.out.println("集合中的元素有:" + c1); // [啥也没有]
      
      System.out.println("--------------------------------------------------------");
      // 2.向集合中添加单个元素并打印
      boolean b1 = c1.add(new String("one"));
      System.out.println("b1 = " + b1); // true
      System.out.println("集合中的元素有:" + c1); // [one]
      
      b1 = c1.add(Integer.valueOf(2));
      System.out.println("b1 = " + b1); // true
      System.out.println("集合中的元素有:" + c1); // [one, 2]
      
      b1 = c1.add(new Person("zhangfei", 30));
      System.out.println("b1 = " + b1); // true
      // 打印集合中的所有元素时,本质上就是打印集合中的每个对象,也就是让每个对象调用对应类的toString方法
      System.out.println("集合中的元素有:" + c1); // [one, 2, Person{name='zhangfei', age=30}]
      
      System.out.println("--------------------------------------------------------");
      // 3.向集合中添加多个元素并打印
      Collection c2 = new ArrayList();
      c2.add("three");  // 常量池
      c2.add(4);        // 自动装箱机制
      System.out.println("c2 = " + c2); // [three, 4]
      // 将c2中的所有元素全部添加到集合c1中,也就是将集合c2中的元素一个一个依次添加到集合c1中
      b1 = c1.addAll(c2);
      // 表示将集合c2整体看做一个元素添加到集合c1中
      //b1 = c1.add(c2);//[one, 2, Person{name='zhangfei', age=30}, [three, 4]]
      System.out.println("b1 = " + b1);//true
      System.out.println("c1 = " + c1);// [one, 2, Person{name='zhangfei', age=30}, three, 4]  
      
      System.out.println("--------------------------------------------------------");
      
    • contains和containsAll

      // 4.判断集合中是否包含参数指定的单个元素
      b1 = c1.contains(new String("one"));
      System.out.println("b1 = " + b1); // true
      
      b1 = c1.contains(new String("two"));
      System.out.println("b1 = " + b1); // false
      
      b1 = c1.contains(Integer.valueOf(2));
      System.out.println("b1 = " + b1); // true
      
      b1 = c1.contains(Integer.valueOf(3));
      System.out.println("b1 = " + b1); // false
      // contains方法的工作原理是:Objects.equals(o, e),其中o代表contains方法的形式参数,e代表集合中的每个元素
      // 也就是contains的工作原理就是 拿着参数对象与集合中已有的元素依次进行比较,比较的方式调用Objects中的equals方法
      // 而该方法equals的工作原理如下:
      /*
              public static boolean equals(Object a, Object b) {    其中a代表Person对象,b代表集合中已有的对象
                  return (a == b) || (a != null && a.equals(b));
                  元素包含的第一种方式就是:Person对象与集合中已有对象的地址相同
                           第二种方式就是:Person对象不为空,则Person对象调用equals方法与集合中已有元素相等
              }
      */
      // 当Person类中没有重写equals方法时,则调用从Object类中继承下来的equals方法,比较两个对象的地址  false
      // 当Person类中重写equals方法后,则调用重写以后的版本,比较两个对象的内容  true
      b1 = c1.contains(new Person("zhangfei", 30));
      System.out.println("b1 = " + b1); // true  false
      
      System.out.println("--------------------------------------------------------");
      // [one, 2, Person{name='zhangfei', age=30}, three, 4]
      System.out.println("c1 = " + c1);
      
      // 5.判断当前集合中是否包含参数指定集合的所有元素
      Collection c3 = new ArrayList();
      c3.add(4);
      System.out.println("c3 = " + c3); // [4]
      
      // 判断集合c1中是否包含集合c3中的所有元素
      b1 = c1.containsAll(c3);
      System.out.println("b1 = " + b1); // true
      
      c3.add("five");
      System.out.println("c3 = " + c3); // [4, five]
      // 判断集合c1中是否包含集合c3中的所有元素,只有集合c3中的所有元素都在集合c1中出现才会返回true,否则都是false
      b1 = c1.containsAll(c3);
      System.out.println("b1 = " + b1); // false
      
      // 笔试考点
      System.out.println("c2 = " + c2); // [three, 4]
      b1 = c1.containsAll(c2);
      System.out.println("b1 = " + b1); // true
      // 判断集合c1中是否拥有集合c2这个整体为单位的元素
      b1 = c1.contains(c2);
      System.out.println("b1 = " + b1); // false
      
      System.out.println("--------------------------------------------------------");
      
    • 集合交集的方法retainAll

      // 6.计算两个集合的交集并保留到当前集合中
      System.out.println("c2 = " + c2); // [three, 4]
      System.out.println("c3 = " + c3); // [4, five]
      // 也就是让集合自己和自己取交集,还是自己,也就是当前集合中的元素没有发生改变
      b1 = c2.retainAll(c2);
      System.out.println("b1 = " + b1); // false 表示当前集合中的元素没有发生改变
      System.out.println("c2 = " + c2); // [three, 4]
      // 计算集合c2和c3的交集并保留到集合c2中,取代集合c2中原有的数值
      b1 = c2.retainAll(c3);
      System.out.println("b1 = " + b1); // true 当前集合的元素发生了改变
      System.out.println("c2 = " + c2); // [4]
      System.out.println("c3 = " + c3); // [4, five]
      
      System.out.println("--------------------------------------------------------");
      
    • remove和removeAll

      // 7.实现集合中单个元素的删除操作
      // [one, 2, Person{name='zhangfei', age=30}, three, 4]
      System.out.println("c1 = " + c1);
      // 删除参数指定的单个元素
      b1 = c1.remove(1);
      System.out.println("b1 = " + b1); // false
      // [one, 2, Person{name='zhangfei', age=30}, three, 4]
      System.out.println("c1 = " + c1);
      
      b1 = c1.remove("one");
      System.out.println("b1 = " + b1); // true
      // [2, Person{name='zhangfei', age=30}, three, 4]
      System.out.println("c1 = " + c1);
      
      // remove方法的工作原理:Objects.equals(o, e)
      b1 = c1.remove(new Person("zhangfei", 30));
      System.out.println("b1 = " + b1); // true
      // [2, three, 4]
      System.out.println("c1 = " + c1);
      
      System.out.println("--------------------------------------------------------");
      // 8.实现集合中所有元素的删除操作
      System.out.println("c3 = " + c3); // [4, five]
      // 从集合c1中删除集合c3中的所有元素,本质上就是一个一个元素进行删除,有元素则删除,否则不删除
      b1 = c1.removeAll(c3);
      System.out.println("b1 = " + b1); // true
      // [2, three]
      System.out.println("c1 = " + c1);
      System.out.println("c3 = " + c3); // [4, five]
      
      // 笔试考点  删除整体对象c3
      b1 = c1.remove(c3);
      System.out.println("b1 = " + b1); // false
      System.out.println("c1 = " + c1); // [2, three]
      
      System.out.println("--------------------------------------------------------");
      
    • size、isEmpty、clear、equals

      // 9.实现集合中其它方法的测试   ctrl+n 可以直接搜索并打开类的源码  使用ctrl+f12可以搜索类中的方法
      System.out.println("集合中元素的个数为:" + c1.size()); // 2
      System.out.println(0 == c1.size() ? "集合已经空了": "集合还没有空"); // 没有空
      System.out.println(c1.isEmpty()? "集合已经空了": "集合还没有空"); // 没有空
      // 清空集合中的所有元素
      c1.clear();
      System.out.println("集合中元素的个数为:" + c1.size()); // 0
      System.out.println(0 == c1.size() ? "集合已经空了": "集合还没有空"); // 已经空了
      System.out.println(c1.isEmpty()? "集合已经空了": "集合还没有空");   // 已经空了
      
      // 准备两个集合并判断是否相等
      Collection c4 = new ArrayList();
      c4.add(1);
      c4.add(2);
      System.out.println("c4 = " + c4); // [1, 2]
      Collection c5 = new ArrayList();
      c5.add(1);
      c5.add(2);
      c5.add(3);
      System.out.println("c5 = " + c5); // [1, 2, 3]
      // 判断是否相等
      b1 = c4.equals(c5);
      System.out.println("b1 = " + b1); //false
      
      System.out.println("--------------------------------------------------------");
      
    • Collection集合与Object数组之间的相互转换

      // 10.实现集合和数组类型之间的转换   通常认为:集合是用于取代数组的结构
      // 实现集合向数组类型的转换
      Object[] objects = c5.toArray();
      // 打印数组中的所有元素
      System.out.println("数组中的元素有:" + Arrays.toString(objects)); // [1, 2, 3]
      // 实现数组类型到集合类型的转换
      Collection objects1 = Arrays.asList(objects);
      System.out.println("集合中的元素有:" + objects1); // [1, 2, 3]
      

3. Iterator接口

  • 常用方法

    boolean hasNext() 判断集合中是否有可以迭代/访问的元素,判断的是指针当前指向元素的下一个元素,最初指针位置在集合中第一个元素的前一个位置(集合对象调用iterator方法时指针指向这个位置)

    E next() 用于取出一个元素并指向下一个元素,每一次调用next方法后指针指向下一个元素

    void remove() 用于删除访问到的最后一个元素,用迭代器对集合进行迭代时用集合中方法删除元素会产生并发异常,推荐用该方法删除

    // 1.准备一个Collection集合并放入元素后打印
    Collection c1 = new ArrayList();
    c1.add("one");
    c1.add(2);
    c1.add(new Person("zhangfei", 30));
    // 遍历方式一: 自动调用toString方法   String类型的整体
    System.out.println("c1 = " + c1); // [one, 2, Person{name='zhangfei', age=30}]
    
    System.out.println("------------------------------------------------");
    // 2.遍历方式二:使用迭代器来遍历集合中的所有元素  更加灵活
    // 2.1 获取当前集合中的迭代器对象
    Iterator iterator1 = c1.iterator();
    /*
            // 2.2 判断是否有元素可以访问
            System.out.println(iterator1.hasNext()); // true
            // 2.3 取出一个元素并指向下一个
            System.out.println("获取到的元素是:" + iterator1.next()); // one
    
            System.out.println(iterator1.hasNext()); // true
            System.out.println("获取到的元素是:" + iterator1.next()); // 2
    
            System.out.println(iterator1.hasNext()); // true
            System.out.println("获取到的元素是:" + iterator1.next()); // Person{name='zhangfei', age=30}
    
            System.out.println(iterator1.hasNext()); // false
            System.out.println("获取到的元素是:" + iterator1.next()); // 编译ok,运行发生NoSuchElementException没有这样的元素异常
             */
    while (iterator1.hasNext()) {
        System.out.println("获取到的元素是:" + iterator1.next());
    }
    
    System.out.println("------------------------------------------------");
    // 由于上个循环已经使得迭代器走到了最后,因此需要重置迭代器
    iterator1 = c1.iterator();
    // 3.使用迭代器来模拟toString方法的打印效果
    StringBuilder sb1 = new StringBuilder();
    sb1.append("[");
    while (iterator1.hasNext()) {
        Object obj = iterator1.next();
        // 当获取的元素是最后一个元素时,则拼接元素加中括号
        if (!iterator1.hasNext()) {
            sb1.append(obj).append("]");
        } else {
            // 否则拼接元素加逗号加空格
            sb1.append(obj).append(",").append(" ");
        }
    }
    // [one, 2, Person{name='zhangfei', age=30}]
    System.out.println("c1 = " + sb1);
    
    System.out.println("------------------------------------------------");
    // 4.不断地去获取集合中的元素并判断,当元素值为"one"时则删除该元素
    iterator1 = c1.iterator();
    while (iterator1.hasNext()) {
        Object obj = iterator1.next();
        if("one".equals(obj)) {
            iterator1.remove();  //使用迭代器的remove方法删除元素没问题
            //c1.remove(obj); // 使用集合的remove方法编译ok,运行发生ConcurrentModificationException并发修改异常
        }
    }
    System.out.println("删除后集合中的元素有:" + c1); // [2, Person{name='zhangfei', age=30}]
    
    System.out.println("------------------------------------------------");
    

4. for each循环

  • for each与迭代器的关系:编译器会将for each转换为带有迭代器的循环

    for each的执行流程:不断地从数组/集合中取出一个元素赋值给变量名并执行循环体,直到取完所有元素为止

    // 5.使用 for each结构实现集合和数组中元素的遍历  代码简单且方法灵活
    // 由打断点调试源码可知:该方式确实是迭代器的简化版
    for (Object obj : c1) {
        System.out.println("取出来的元素是:" + obj);
    }
    
    int[] arr = new int[] {11, 22, 33, 44, 55};
    for (int i : arr) {
        System.out.println("i = " + i);
        i = 66; // 修改局部变量i的数值,并不是修改数组中元素的数值
    }
    System.out.println("数组中的元素有:" + Arrays.toString(arr));
    

5. List集合

  • ArrayList和LinkedList

    public class ListTest {
    
        public static void main(String[] args) {
    
            // 1.声明一个List接口类型的引用指向ArrayList类型的对象,形成了多态
            // 由源码可知:当new对象时并没有申请数组的内存空间
            List lt1 = new ArrayList();
            // 2.向集合中添加元素并打印
            // 由源码可知:当调用add方法添加元素时会给数组申请长度为10的一维数组,扩容原理是:原始长度的1.5倍
            lt1.add("one");
            System.out.println("lt1 = " + lt1); // [one]
    
            System.out.println("----------------------------------------------------");
            // 2.声明一个List接口类型的引用指向LinkedList类型的对象,形成了多态
            List lt2 = new LinkedList();
            lt2.add("one");
            System.out.println("lt2 = " + lt2); // [one]
        }
    }
    
  • Stack和Vector

    • ArrayList和Vector用法相似,ArrayList扩容倍数1.5,Vector扩容倍数是2,ArrayList效率较高,目前Vector大部分使用场景已经被ArrayList取代
    • 开发中Stack几乎已被Deque取代
    • Stack 类继承自 Vector 类
  • List中的常用方法

    • add和get

      // 1.准备一个List集合并打印
      List lt1 = new LinkedList();
      System.out.println("lt1 = " + lt1); // [啥也没有]
      
      System.out.println("------------------------------------------");
      // 2.向集合中添加元素并打印
      // 向集合中的开头位置添加元素
      lt1.add(0, "one");
      System.out.println("lt1 = " + lt1); // [one]
      // 向集合中的末尾位置添加元素
      lt1.add(1, 3);
      System.out.println("lt1 = " + lt1); // [one, 3]
      // 向集合中的中间位置添加元素
      lt1.add(1, "two");
      System.out.println("lt1 = " + lt1); // [one, two, 3]
      
      System.out.println("------------------------------------------");
      // 3.根据参数指定的下标来获取元素
      String str1 = (String) lt1.get(0);
      System.out.println("获取到的元素是:" + str1); // one
      
      // 注意:获取元素并进行强制类型转换时一定要慎重,因为容易发生类型转换异常
      //String str2 = (String)lt1.get(2); // 编译ok,运行发生ClassCastException类型转换异常
      //System.out.println("获取到的元素是:" + str2); // 3
      
      System.out.println("------------------------------------------");
      // 4.使用get方法获取集合中的所有元素并打印
      StringBuilder sb1 = new StringBuilder();
      sb1.append("[");
      for (int i = 0; i < lt1.size(); i++) {
          //Object obj = lt1.get(i);
          //System.out.println("获取到的元素是:" + obj);
          Object obj = lt1.get(i);
          // 若取出的元素是最后一个元素,则拼接元素值和]
          if (lt1.size()-1 == i) {
              sb1.append(obj).append("]");
          }
          // 否则拼接元素和逗号以及空格
          else {
              sb1.append(obj).append(",").append(" ");
          }
      }
      System.out.println("lt1 = " + sb1); // [one, two, 3]
      
      System.out.println("------------------------------------------");
      
    • 查找indexOf、set、remove、subList

      // 5.查找指定元素出现的索引位置
      System.out.println("one第一次出现的索引位置为:" + lt1.indexOf("one")); // 0
      lt1.add("one");
      System.out.println("lt1 = " + lt1); // [one, two, 3, one]
      System.out.println("one反向查找第一次出现的索引位置是:" + lt1.lastIndexOf("one")); // 3
      
      System.out.println("------------------------------------------");
      System.out.println("lt1 = " + lt1); // [one, two, 3, one]
      // 6.实现集合中元素的修改
      Integer it1 = (Integer) lt1.set(2, "three");
      System.out.println("被修改的元素是:" + it1); // 3
      System.out.println("修改后集合中的元素有:" + lt1); // [one, two, three, one]
      
      String str2 = (String) lt1.set(3, "four");
      System.out.println("被修改的元素是:" + str2); // one
      System.out.println("修改后集合中的元素有:" + lt1); // [one, two, three, four]
      
      System.out.println("------------------------------------------");
      // 7.使用remove方法将集合中的所有元素删除
      //for (int i = 0; i < lt1.size(); /*i++*/) {
      /* for (int i = lt1.size()-1; i >= 0; i--) {
        	//System.out.println("被删除的元素是:" + lt1.remove(i)); // one  two  three  four 删除元素后,后面的元素补位
          //System.out.println("被删除的元素是:" + lt1.remove(0));
            System.out.println("被删除的元素是:" + lt1.remove(i));
      }
      System.out.println("最终集合中的元素有:" + lt1); // [啥也没有]
      */
      
      System.out.println("------------------------------------------");
      // 8.获取当前集合中的子集合,也就是将集合中的一部分内容获取出来,子集合和当前集合共用同一块内存空间
      // 表示获取当前集合lt1中下标从1开始到3之间的元素,包含1但不包含3
      List lt2 = lt1.subList(1, 3);
      System.out.println("lt2 = " + lt2); // [two, three]
      // 删除lt2中元素的数值
      str2 = (String) lt2.remove(0);
      System.out.println("被删除的元素是:" + str2); // two
      System.out.println("删除后lt2 = " + lt2); // [three]
      System.out.println("删除后lt1 = " + lt1); // [one, three, four]
      
  • Stack

    • 案例:准备一个Stack集合,将数据11、22、33、44、55依次入栈并打印,然后查看栈顶元素并打印,

      然后将栈中所有数据依次出栈并打印。再准备一个Stack对象,将数据从第一个栈中取出来放入第二个栈中,然后再从第二个栈中取出并打印

      public static void main(String[] args) {
      
          // 1.准备一个Stack类型的对象并打印
          Stack s1 = new Stack();
          Stack s2 = new Stack();
          System.out.println("s1 = " + s1); // [啥也没有]
          System.out.println("s2 = " + s2); // [啥也没有]
      
          System.out.println("-----------------------------------------------");
          // 2.将数据11、22、33、44、55依次入栈并打印
          for (int i = 1; i <= 5; i++) {
              Object obj = s1.push(i * 11);
              System.out.println("入栈的元素是:" + obj);
              //System.out.println("栈中的元素有:" + s1); // 11 22 33 44 55
          }
      
          System.out.println("-----------------------------------------------");
          // 3.查看栈顶元素值并打印
          //Object obj2 = s1.peek();
          //System.out.println("获取到的栈顶元素是:" + obj2); // 55
      
          System.out.println("-----------------------------------------------");
          // 4.对栈中所有元素依次出栈并打印
          int len = s1.size();
          for (int i = 1; i <= len; i++) {
              Object to = s1.pop();
              //System.out.println("出栈的元素是:" + to); // 55 44 33 22 11
              s2.push(to);
          }
      
          System.out.println("-----------------------------------------------");
          // 5.最终打印栈中的所有元素
          //System.out.println("s1 = " + s1); // [啥也没有]
      
          System.out.println("-----------------------------------------------");
          len = s2.size();
          for (int i = 1; i <= len; i++) {
              Object to = s2.pop();
              System.out.println("出栈的元素是:" + to); // 11 22 33 44 55
          }
      }
      /*
      s1 = []
      s2 = []
      -----------------------------------------------
      入栈的元素是:11
      入栈的元素是:22
      入栈的元素是:33
      入栈的元素是:44
      入栈的元素是:55
      -----------------------------------------------
      -----------------------------------------------
      -----------------------------------------------
      -----------------------------------------------
      出栈的元素是:11
      出栈的元素是:22
      出栈的元素是:33
      出栈的元素是:44
      出栈的元素是:55
      */
      

6. Queue集合

  • java.util.Queue集合是Collection集合的子集合,与List集合属于平级关系

    该集合的主要实现类是LinkedList类,因为该类在增删方面比较有优势

  • 案例:准备一个Queue集合,将数据11、22、33、44、55依次入队并打印,然后查看队首元素并打印,然后将队列中所有数据依次出队并打印

    public static void main(String[] args) {
    
        // 1.准备一个Queue集合并打印
        Queue queue = new LinkedList();
        System.out.println("队列中的元素有:" + queue); // [啥也没有]
    
        System.out.println("----------------------------------------------------------");
        // 2.将数据11、22、33、44、55依次入队并打印
        for (int i = 1; i <= 5; i++) {
            boolean b1 = queue.offer(i * 11);
            //System.out.println("b1 = " + b1);
            System.out.println("队列中的元素有:" + queue); // 11 22 33 44 55
        }
    
        System.out.println("----------------------------------------------------------");
        // 3.然后查看队首元素并打印
        System.out.println("对首元素是:" + queue.peek()); // 11
    
        System.out.println("----------------------------------------------------------");
        // 4.然后将队列中所有数据依次出队并打印
        int len = queue.size();
        for (int i = 1; i <= len; i++) {
            System.out.println("出队的元素是:" + queue.poll()); // 11 22 33 44 55
        }
    
        System.out.println("----------------------------------------------------------");
        // 5.查看队列中最终的元素
        System.out.println("队列中的元素有:" + queue); // [啥也没有]
    }
    /*
    队列中的元素有:[]
    ----------------------------------------------------------
    队列中的元素有:[11]
    队列中的元素有:[11, 22]
    队列中的元素有:[11, 22, 33]
    队列中的元素有:[11, 22, 33, 44]
    队列中的元素有:[11, 22, 33, 44, 55]
    ----------------------------------------------------------
    对首元素是:11
    ----------------------------------------------------------
    出队的元素是:11
    出队的元素是:22
    出队的元素是:33
    出队的元素是:44
    出队的元素是:55
    ----------------------------------------------------------
    队列中的元素有:[]
    */
    

五、集合类库(二)

1. 泛型机制

  • 泛型原理

    泛型的本质就是参数化类型,也就是让数据类型作为参数传递,其中E相当于形式参数负责占位,而使用集合时<>中的数据类型相当于实际参数,用于给形式参数E进行初始化,从而使得集合中所有的E被实际参数替换,由于实际参数可以传递各种各样广泛的数据类型,因此得名为泛型

  • 泛型机制的基本使用

    • 带泛型的类只能在new对象时指定具体的类型,访问静态方法的形式不能指定泛型的具体类型

      所以带泛型的类中,静态方法不能有泛型的参数(如:返回值类型不能为泛型),可以正常访问不含泛型参数的静态方法

    • 带泛型的类使用new创建对象是可以不指定泛型具体类型,此时默认指定泛型类型为

      public static void main(String[] args) {
      
          // 1.准备一个支持泛型机制的List集合,明确要求集合中的元素是String类型
          List lt1 = new LinkedList();
          // 2.向集合中添加元素并打印
          lt1.add("one");
          System.out.println("lt1 = " + lt1); // [one]
          //lt1.add(2);  Error
          // 3.获取集合中的元素并打印
          String s = lt1.get(0);
          System.out.println("获取到的元素是:" + s); // one
      
          System.out.println("----------------------------------------------------");
          // 2.准备一个支持Integer类型的List集合
          List lt2 = new LinkedList();
          lt2.add(1);
          lt2.add(2);
          //lt2.add("3"); Error
          System.out.println("lt2 = " + lt2); // [1, 2]
          Integer integer = lt2.get(0);
          System.out.println("获取到的元素是:" + integer); // 1
      
          System.out.println("----------------------------------------------------");
          // Java7开始的新特性: 菱形特性   就是后面<>中的数据类型可以省略
          List lt3 = new LinkedList<>();
          // 笔试考点
          // 试图将lt1的数值赋值给lt3,也就是覆盖lt3中原来的数值,结果编译报错:集合中支持的类型不同
          //lt3 = lt1; Error
      }
      
    • 自定义泛型类和使用泛型类

      /**
       * 自定义泛型类Person,其中T相当于形式参数负责占位,具体数值由实参决定
       * @param  看做是一种名字为T的数据类型即可
       */
      public class Person {
          private String name;
          private int age;
          private T gender;
      
          public Person() {
          }
      
          public Person(String name, int age, T gender) {
              this.name = name;
              this.age = age;
              this.gender = gender;
          }
      
          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;
          }
      
          // 不是泛型方法,该方法不能使用static关键字修饰,因为该方法中的T需要在new对象时才能明确类型
          public /*static*/ T getGender() {
              return gender;
          }
      
          public void setGender(T gender) {
              this.gender = gender;
          }
      
          // 自定义方法实现将参数指定数组中的所有元素打印出来
          public static  void printArray(T1[] arr) {
              for (T1 tt: arr) {
                  System.out.println("tt = " + tt);
              }
          }
      
          @Override
          public String toString() {
              return "Person{" +
                      "name='" + name + '\'' +
                      ", age=" + age +
                      ", gender=" + gender +
                      '}';
          }
      }
      
      public class PersonTest {
      
          public static void main(String[] args) {
      
              // 1.声明Person类型的引用指向Person类型的对象,可以不指定泛型的类型就默认为Object类型
              Person p1 = new Person("zhangfei", 30, "男");
              // 2.打印对象的特征
              System.out.println(p1); // zhangfei 30 男
      
              System.out.println("-----------------------------------");
              // 3.在创建对象的同时指定数据类型,用于给T进行初始化
              Person p2 = new Person<>();
              p2.setGender("女");
              System.out.println(p2); // null  0  女
      
              System.out.println("-----------------------------------");
              // 4.使用Boolean类型作为性别的类型
              Person p3 = new Person<>();
              p3.setGender(true);
              System.out.println(p3); // null 0  true
      
              System.out.println("-----------------------------------");
              // 5.调用泛型方法进行测试
              Integer[] arr = {11, 22, 33, 44, 55};
              Person.printArray(arr); // 11 22 33 44 55
          }
      }
      
    • 泛型类被继承时的处理方式

      父类有泛型,子类可以选择保留泛型也可以选择指定泛型类型

      子类必须是“富二代”,子类除了指定或保留父类的泛型,还可以增加自己的泛型

      //public class SubPerson extends Person { // 不保留泛型并且没有指定类型,此时Person类中的T默认为Object类型,也叫擦除
      //public class SubPerson extends Person {  // 不保留泛型但指定了泛型的类型,此时Person类中的T被指定String类型
      //public class SubPerson extends Person { // 保留父类的泛型  可以在构造对象时来指定T的类型
      public class SubPerson extends Person { // 保留父类的泛型,同时在子类中增加新的泛型
      }
      
      public class SubPersonTest {
          public static void main(String[] args) {
              //当子类中有定义泛型,可以不指定具体类型,默认为类型,此时父类也是,调用父类带参数的方法传参也是按Object类型进行传参
              SubPerson objectObjectSubPerson = new SubPerson<>();
              objectObjectSubPerson.setGender("male");
              objectObjectSubPerson.setGender(1);
              objectObjectSubPerson.setGender(true);
      
            //按子类指定的第一个类型来决定父类泛型类型,所以以这里调用带参数的父类方法,传第一个类型String的参数
              SubPerson objectObjectSubPerson1 = new SubPerson<>();
              objectObjectSubPerson1.setGender("female");
      
            //按子类指定的第一个类型来决定父类泛型类型,所以以这里调用带参数的父类方法,传第一个类型Integer的参数
              SubPerson objectObjectSubPerson2 = new SubPerson<>();
              objectObjectSubPerson2.setGender(1);
              
          }
      }
      
      
      
    • 自定义泛型方法

      泛型方法就是输入参数的时候,输入的是泛型参数,而不是具体的参数。我们在调用这个泛型方法的时需要对泛型参数进行实例化

      //不是泛型方法,该方法在创建对象时会将形参T初始化为指定的类型
      public T getGender() {
          return gender;
      }
      
      // 自定义方法实现将参数指定数组中的所有元素打印出来
      //格式:访问权限+<泛型>+返回值类型,这里指定泛型表示该类型不是Java官方的类型也不是类指定的泛型
      public static  void printArray(T1[] arr) {
          for (T1 tt: arr) {
              System.out.println("tt = " + tt);
          }
      }
      
      //泛型方法的使用:直接传入具体类型的参数,自动匹配类型
      Integer[] arr = {11, 22, 33, 44, 55};
      Person.printArray(arr); // 11 22 33 44 55
      
      // 不是泛型方法,该方法不能使用static关键字修饰,因为该方法中的T需要在new对象时才能明确类型
      public /*static*/ T getGender() {
          return gender;
      }
      
    • 泛型通配符

      <?>无限制通配符,作为引用变量可以用来接收不同泛型的变量,不支持添加元素,支持元素的获取且返回值为Object类型

      <? extend E>E表示上界,作为引用变量可以接收的泛型只能是E或E的子类,不支持添加元素,支持元素的获取且返回值为E类型

      <? super E>E表示下界,作为引用变量可以接收的泛型只能是E或E的父类,支持添加元素(Object类型不支持),支持元素的获取且返回值为Object类型

      看能否添加元素,主要取决于,当前泛型通配符作为父类类型能否指向其子类对象

      public class GenericTest {
      
          public static void main(String[] args) {
      
              // 1.声明两个List类型的集合进行测试
              List lt1 = new LinkedList<>();
              List lt2 = new LinkedList<>();
              // 试图将lt2的数值赋值给lt1,也就是发生List类型向List类型的转换
              //lt1 = lt2;  Error: 类型之间不具备父子类关系
      
              System.out.println("---------------------------------------------");
              // 2.使用通配符作为泛型类型的公共父类
              List<?> lt3 = new LinkedList<>();
              lt3 = lt1; // 可以发生List类型到List<?>类型的转换
              lt3 = lt2; // 可以发生List类型到List<?>类型的转换
      
              // 向公共父类中添加元素和获取元素
              //lt3.add(new Animal()); Error: 不能存放Animal类型的对象
              //lt3.add(new Dog());    Error: 不能存放Dog类型的对象, 不支持元素的添加操作
      
              Object o = lt3.get(0);  // ok,支持元素的获取操作,全部当做Object类型来处理
      
              System.out.println("---------------------------------------------");
              // 3.使用有限制的通配符进行使用
              List<? extends Animal> lt4 = new LinkedList<>();
              // 不支持元素的添加操作
              //lt4.add(new Animal());
              //lt4.add(new Dog());
              //lt4.add(new Object());
              // 获取元素
              Animal animal = lt4.get(0);
      
              System.out.println("---------------------------------------------");
              List<? super Animal> lt5 = new LinkedList<>();
              lt5.add(new Animal());
              lt5.add(new Dog());
              //lt5.add(new Object());  Error: 超过了Animal类型的范围
              Object object = lt5.get(0);
          }
      }
      
    • 2. Set集合

      • Set集合中元素没有先后放入次序,且不允许重复,开发中使用Set主要目的是去重

      • HashSet和LinkedHashSet

        public class HashSetTest {
        
            public static void main(String[] args) {
        
                // 1.声明一个Set类型的引用指向HashSet类型的对象
                Set s1 = new HashSet<>();
                //Set s1 = new LinkedHashSet<>();  // 将放入的元素使用双链表连接起来
                System.out.println("s1 = " + s1); // [啥也没有]
        
                System.out.println("----------------------------------------------------");
                // 2.向集合中添加元素并打印
                boolean b1 = s1.add("two");
                System.out.println("b1 = " + b1); // true
                System.out.println("s1 = " + s1); // [two]
                // 从打印结果上可以看到元素没有先后放入次序(表面)
                b1 = s1.add("one");
                System.out.println("b1 = " + b1); // true
                System.out.println("s1 = " + s1); // [one, two]   [two, one]
        
                b1 = s1.add("three");
                System.out.println("b1 = " + b1); // true
                System.out.println("s1 = " + s1); // [one, two, three]  [two, one, three]
                // 验证元素不能重复
                b1 = s1.add("one");
                System.out.println("b1 = " + b1); // false
                System.out.println("s1 = " + s1); // [one, two, three] [two, one, three]
            }
        }
        
      • TreeSet

        • 由于TreeSet集合的底层采用红黑树进行数据的管理,当有新元素插入到TreeSet集合时,需要使用新元素与集合中已有的元素依次比较来确定新元素的合理位置

          // 1.准备一个TreeSet集合并打印
          Set s1 = new TreeSet<>();
          System.out.println("s1 = " + s1); // [啥也没有]
          
          // 2.向集合中添加String类型的对象并打印
          boolean b1 = s1.add("aa");
          System.out.println("b1 = " + b1); // true
          System.out.println("s1 = " + s1); // [aa]
          
          b1 = s1.add("cc");
          System.out.println("b1 = " + b1); // true
          System.out.println("s1 = " + s1); // [aa, cc]
          
          b1 = s1.add("bb");
          System.out.println("b1 = " + b1); // true
          // 由于TreeSet集合的底层是采用红黑树实现的,因此元素有大小次序,默认从小到大打印
          //TreeSet中元素类型为String,String中实现了Comparable接口,使用元素的自然排序规则进行比较和排序
          System.out.println("s1 = " + s1); // [aa, bb, cc]
          
        • TreeSet中实现自然排序和比较器排序

          实现自然排序:在元素类中实现Comparable接口,重写comparaTo方法

          实现比较器排序:创建Comparator对象,重写compare方法,创建TreeSet对象时传入Comparator对象

          同时实现自然排序和比较器排序时,比较器优先于自然排序

          String中实现了Comparable接口,使用元素的自然排序规则进行比较和排序//在Student类中实现Comparable,重写compareTo方法
          @Override
          public int compareTo(Student o) {
              //return 0;   // 调用对象和参数对象相等,调用对象就是新增加的对象
              //return -1;  // 调用对象小于参数对象
              //return 1;     // 调用对象大于参数对象
              //return this.getName().compareTo(o.getName());  // 比较姓名
              //return this.getAge() - o.getAge(); // 比较年龄
              /*
                  int ia = this.getName().compareTo(o.getName());
                  if (0 == ia) {
                      return this.getAge() - o.getAge();
                  }
                  return ia;
                   */
              int ia = this.getName().compareTo(o.getName());//String中实现了Comparable接口,使用元素的自然排序规则进行比较和排序
              return 0 != ia? ia : this.getAge() - o.getAge();
          }
          
          System.out.println("----------------------------------------------------------");
          // 4.准备一个比较器对象作为参数传递给构造方法
          // 匿名内部类: 接口/父类类型 引用变量名 = new 接口/父类类型() { 方法的重写 };
          /*
                  Comparator comparator = new Comparator() {
                      @Override
                      public int compare(Student o1, Student o2) {  // o1表示新增加的对象  o2表示集合中已有的对象
                          return o1.getAge() - o2.getAge(); // 表示按照年龄比较
                      }
                  };
                  */
          // 从Java8开始支持Lambda表达式: (参数列表) -> { 方法体 }
          Comparator comparator = (Student o1, Student o2) -> { return o1.getAge() - o2.getAge(); };
          
          // 3.准备一个TreeSet集合并放入Student类型的对象并打印
          //Set s2 = new TreeSet<>();
          Set s2 = new TreeSet<>(comparator);
          s2.add(new Student("zhangfei", 35));
          s2.add(new Student("zhangfei", 30));
          s2.add(new Student("guanyu", 35));
          s2.add(new Student("liubei", 40));
          System.out.println("s2 = " + s2);
          /*
          s2 = [Student{age=30, name='zhangfei'}, Student{age=35, name='zhangfei'}, Student{age=40, name='liubei'}]
          */
          

      3. Map集合

      • Map中常用方法

        • Map中元素的增加、修改、查找、删除

          // 1.准备一个Map集合并打印
          Map m1 = new HashMap<>();
          // 自动调用toString方法,默认打印格式为:{key1=value1, key2=value2, ...}
          System.out.println("m1 = " + m1); // {啥也没有}
          
          // 2.向集合中添加元素并打印
          String str1 = m1.put("1", "one");
          System.out.println("原来的value数值为:" + str1); // null
          System.out.println("m1 = " + m1); // {1=one}
          
          str1 = m1.put("2", "two");
          System.out.println("原来的value数值为:" + str1); // null
          System.out.println("m1 = " + m1); // {1=one, 2=two}
          
          str1 = m1.put("3", "three");
          System.out.println("原来的value数值为:" + str1); // null
          System.out.println("m1 = " + m1); // {1=one, 2=two, 3=three}
          // 实现了修改的功能
          str1 = m1.put("1", "eleven");
          System.out.println("原来的value数值为:" + str1); // one
          System.out.println("m1 = " + m1); // {1=eleven, 2=two, 3=three}
          
          System.out.println("-------------------------------------------------------------");
          // 3.实现集合中元素的查找操作
          boolean b1 = m1.containsKey("11");
          System.out.println("b1 = " + b1); // false
          b1 = m1.containsKey("1");
          System.out.println("b1 = " + b1); // true
          
          b1 = m1.containsValue("one");
          System.out.println("b1 = " + b1); // false
          b1 = m1.containsValue("eleven");
          System.out.println("b1 = " + b1); // true
          
          String str2 = m1.get("5");
          System.out.println("str2 = " + str2); // null
          str2 = m1.get("3");
          System.out.println("str2 = " + str2); // three
          
          System.out.println("-------------------------------------------------------------");
          // 4.实现集合中元素的删除操作
          str2 = m1.remove("1");
          System.out.println("被删除的value是:" + str2); // eleven
          System.out.println("m1 = " + m1); // {2=two, 3=three}
          
          System.out.println("-------------------------------------------------------------");
          
        • Map的遍历相关4种方法

          // 5.获取Map集合中所有的key并组成Set视图
          Set s1 = m1.keySet();
          // 遍历所有的key
          for (String ts : s1) {
              System.out.println(ts + "=" + m1.get(ts));
          }
          
          System.out.println("-------------------------------------------------------------");
          // 6.获取Map集合中所有的Value并组成Collection视图
          Collection co = m1.values();
          for (String ts : co) {
              System.out.println("ts = " + ts);
          }
          
          System.out.println("-------------------------------------------------------------");
          // 7.获取Map集合中所有的键值对并组成Set视图
          //Entry是Map中的内部接口
          Set> entries = m1.entrySet();
          for (Map.Entry me : entries) {
              System.out.println(me);
          }
          
          //HashMap
          System.out.println(m1);
          
          /*
          2=two
          3=three
          -------------------------------------------------------------
          ts = two
          ts = three
          -------------------------------------------------------------
          2=two
          3=three
          
          {2=two, 3=three}
          */
          

      4. Collections类

      • java.util.Collections类主要提供了对集合操作或者返回集合的静态方法

        public class CollectionsTest {
        
            public static void main(String[] args) {
        
                // 1.准备一个集合并初始化
                List lt1 = Arrays.asList(10, 30, 20, 50, 45);
                // 2.实现集合中元素的各种操作
                System.out.println("集合中的最大值是:" + Collections.max(lt1)); // 50
                System.out.println("集合中的最小值是:" + Collections.min(lt1)); // 10
        
                // 实现集合中元素的反转
                Collections.reverse(lt1);
                System.out.println("lt1 = " + lt1); // [45, 50, 20, 30, 10]
                // 实现两个元素的交换
                Collections.swap(lt1, 0, 4);
                System.out.println("交换后:lt1 = " + lt1); // [10, 50, 20, 30, 45]
                // 实现元素的排序
                Collections.sort(lt1);
                System.out.println("排序后:lt1 = " + lt1); // [10, 20, 30, 45, 50]
                // 随机置换
                Collections.shuffle(lt1);
                System.out.println("随机置换后:lt1 = " + lt1); // [30, 10, 45, 20, 50] 随机
                // 实现集合间元素的拷贝
                //List lt2 = new ArrayList<>(20);
                List lt2 = Arrays.asList(new Integer[10]);
                System.out.println("lt1的大小是:" + lt1.size());
                System.out.println("lt2的大小是:" + lt2.size());
                // 表示将lt1中的元素拷贝到lt2中
                Collections.copy(lt2, lt1);
                System.out.println("lt2 = " + lt2);
            }
        }