Java - Java进阶_常用API(四) String、StringBuilder、Object、Objects、Math、Random

一、API介绍

API(Application Programming Interface) : 应用程序编程接口
    就是别人写好的一些类,我们直接拿来调用即可解决问题的
        
API帮助文档的使用流程

    1. 在索引位置搜索自己要查看的类
        
    2. 看包
            目的: 是不是java.lang包(核心包), 不需要编写导包代码(import)
                    - 不是java.lang包, 都需要编写导包代码
                          
    3. 看这个类的介绍
            目的: 搞清楚这个类的作用
                
    4. 看这个类的构造方法
            目的: 为了将该类的对象, 创建出来
                
    5. 看这个类的成员方法(方法摘要)
            1. 方法名
            2. 参数
            3. 返回值
            4. 介绍

二、Scanner类

Scanner键盘录入的三个步骤
	1. 找符咒
		代码: import java.util.Scanner;
		位置: class的上面
		含义: 能够让自己的类ScannerDemo, 从代码仓库中, 找到Scanner符咒
	2. 召唤精灵
		代码: Scanner sc = new Scanner(System.in);
		位置: main方法里面
		含义: 从符咒中召唤精灵, 给精灵起名字叫做 sc
	
	3. 指挥精灵干活
     	int age = sc.nextInt();             从键盘录入整数, 并使用int类型变量接收
        double height = sc.nextDouble();    从键盘录入小数, 并使用double类型变量接收
        boolean flag  = sc.nextBoolean();   从键盘录入布尔, 并使用boolean类型变量接收
        String name = sc.next();            从键盘录入字符串, 并使用String类型变量接收
            
Scanner键盘录入字符串 :
    String next() : 遇到了空格, 或者是tab键就不再录入了
    String nextLine() : 以回车作为录入的结束标记

    弊端:
            1. next() : 数据可能录入不完整
            2. nextLine() : 之前调用过nextInt(), nextDouble(), nextFloat()...
                                nextLine()方法, 就不干活了

    解决方案: 不用解决
            Scanner : 采集用户信息 (只在学习过程用的到)

    目前的使用方案:
            需求如果要键盘录入字符串
                    如果所有的数据, 全部都是字符串, 直接nextLine();
                            举例:
                                    键盘录入用户名, 键盘录入用户密码

                    如果数据除了字符串, 还有其他类型, 需要调用next()方法
                            举例:
                                    键盘录入用户名, 键盘录入用户年龄, 用户身高
package com.itheima.scanner;

import java.util.Scanner;

public class ScannerDemo1 {
    public static void main(String[] args) {
        // 1. 召唤Scanner精灵
        Scanner sc = new Scanner(System.in);

        // 2. 键盘录入姓名
        System.out.println("请输入您的姓名:");
        String name = sc.next();

        // 3. 键盘录入年龄
        System.out.println("请输入您的年龄:");
        int age = sc.nextInt();

        // 4. 键盘录入性别
        System.out.println("请输入您的性别:");
        String gender = sc.next();

        // 5. 键盘录入身高
        System.out.println("请输入您的身高:");
        double height = sc.nextDouble();

        // 6. 键盘录入婚姻状况
        System.out.println("请输入您的婚姻状况:");
        boolean flag = sc.nextBoolean();

        System.out.println("注册成功!");
        System.out.println(name);
        System.out.println(age);
        System.out.println(gender);
        System.out.println(height);
        System.out.println(flag);
    }
}

三、String类

1、String 类的特点

String类的特点 :
	1. Java 程序中所有双引号字符串, 都是String这个类的对象
	2. 字符串一旦被创建, 就不可更改, 字符串内容不可改变
	    如果想要更改, 只能使用新的对象, 做替换
	3. String字符串虽然不可改变, 但是可以被共享
	    字符串常量池: 当我们使用双引号创建字符串对象时, 会检查常量池中是否存在该数据
	        不存在 : 创建
	        存在 : 复用
package com.itheima.string;

public class StringDemo1 {
    public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "abc";

        System.out.println(s1 == s2); // true
    }
}

2、String 类的常见构造方法

String类常见构造方法 :
	public String() : 创建一个空白字符串, 里面不含任何内容
	public String(char[] chs) : 根据传入的字符数组, 创建字符串对象
	public String(String original) : 根据传入的字符串, 来创建字符串对象
	
	-----------------------------------------------------------------
	
	1. 打印对象名, 会看到对象的内存地址, 这里打印字符串对象, 为什么没有看到地址值
	        回答: 暂不解释
	        TODO: 面向对象(继承), 方法重写, Object类, toString方法
	
	2. 这三个构造方法, 创建字符串对象, 都没有双引号直接创建来的方便.
	        String s = "abc";
	
	-----------------------------------------------------------------
	
	字符串对象, 两种创建方式的区别
	        1. 双引号直接创建
	        2. 通过构造方法创建
package com.itheima.string;

public class StringDemo2 {
    public static void main(String[] args) {
        // public String() : 创建一个空白字符串, 里面不含任何内容
        String s1 = new String();
        System.out.println(s1); // ""

        // public String(char[] chs) : 根据传入的字符数组, 创建字符串对象
        char[] chs = {'a','b','c'};
        String s2 = new String(chs);
        System.out.println(s2); // "abc"

        // public String(String original) : 根据传入的字符串, 来创建字符串对象
        String s3 = new String("abc");
        System.out.println(s3); // "abc"

        String ss1 = "abc";
        String ss2 = "a" + "b" + "c";
        System.out.println(ss1 == ss2); // true
    }
}

3、String 类的常见面试题

在这里插入图片描述
在这里插入图片描述

4、String 类用于比较的方法

String类中用于比较的方法 :
	public boolean equals(Object anObject) 将此字符串与指定的对象比较
	public boolean equalsIgnoreCase(String anotherString) 将此 String 与另一个 String 比较,不考虑大小写
package com.itheima.string.method;

public class StringMethodDemo1 {
    public static void main(String[] args) {

        String s1 = "abc";
        String s2 = new String("abc");

        System.out.println(s1 == s2);               // false
        System.out.println(s1.equals(s2));          // true
        System.out.println("---------------------");

        String ss1 = "abc";
        String ss2 = "ABC";

        System.out.println(ss1.equals(ss2));                // false
        System.out.println(ss1.equalsIgnoreCase(ss2));      // true
    }
}

5、String 字符串的遍历

String类用于遍历的方法:
	public char[] toCharArray() 将此字符串转换为一个新的字符数组
	public char charAt(int index) 返回指定索引处的 char 值
	public int length() 返回此字符串的长度
package com.itheima.string.method;

public class StringMethodDemo2 {
    public static void main(String[] args) {
        print();
    }

    /**
     * 字符串遍历的第二种方式
     */
    private static void print2() {
        String s = "itheima";

        for (int i = 0; i < s.length(); i++) {
            // i = 0 1 2 3 4 5 6
            char c = s.charAt(i);
            System.out.println(c);
        }
    }

    /**
     * 字符串的第一种遍历方式
     */
    private static void print1() {
        String s = "itheima";
        char[] chars = s.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            System.out.println(chars[i]);
        }
    }
}

6、String 字符串的截取方法

String类的截取方法 :
	public String substring(int beginIndex) :  根据传入的索引开始做截取, 截取到字符串的末尾
	public String substring(int beginIndex, int endIndex) :  根据传入的开始和结束索引, 对字符串做截取
	                                                            - 包含头, 不包含尾
	
	注意: 截取出来的内容, 是作为新的字符串返回, 别忘记找变量接收
package com.itheima.string.method;

public class StringMethodDemo3 {
    public static void main(String[] args) {
        String s = "itheima";

        String result = s.substring(0, 2);
        System.out.println(result); // it
    }

    private static void method() {
        String s = "itheima";

        String result = s.substring(2);
        System.out.println(result); // heima
    }
}

7、String 字符串的替换方法

String类的替换方法 :
	public String replace(CharSequence target, CharSequence replacement)
		target : 旧值
		replacement : 新值
package com.itheima.string.method;

public class StringMethodDemo4 {
    public static void main(String[] args) {
        String s = "itheima";

        String result = s.replace("heima", "baima");
        System.out.println(result); // itbaima
    }
}

8、String 字符串的切割方法

String类的切割方法 :
	public String[] split(String regex) : 根据传入的字符串作为规则, 切割当前字符串
		- 建议: 先正常指定切割规则, 后来发现没有得到自己要的效果, 就可以尝试在规则前面, 加入 \\
package com.itheima.string.method;

public class StringMethodDemo5 {
    public static void main(String[] args) {
        String s = "192+168+1+1";
        String[] sArr = s.split("\\+");

        for (int i = 0; i < sArr.length; i++) {
            System.out.println(sArr[i]);
        }
    }
}

9、String字符串的替换方法

String类中与正则有关的常见方法 :
	public String replaceAll(String regex,String newStr) : 按照正则表达式匹配的内容进行替换
package com.itheima.regex;

public class StringRegexMethod {
    public static void main(String[] args) {
        String s = "先帝1创业2未半而中道3崩殂4,今5天下三分6,益州疲弊7,此8诚危急存亡之秋也。然9侍卫之臣不懈于内,忠志之士忘身10于外者,盖追先帝之殊遇11,欲报之于陛下也。诚宜12开张圣听13,以光14先帝遗德,恢弘15志士之气,不宜妄自菲薄16,引喻失义17,以塞忠谏之路也18。\n" +
                "宫中府中,俱为一体19;陟罚臧否20,不宜异同:若有作奸犯科21及为忠善者22,宜付有司23论其刑赏24,以昭陛下平明之理25;不宜偏私26,使内外异法也27。\n" +
                "侍中、侍郎郭攸之、费祎、董允等,此皆良实,志虑忠纯28,是以先帝简拔以遗陛下29:愚以为宫中之事,事无大小,悉以咨之30,然后施行,必能裨补阙漏31,有所广益32";

        s = s.replaceAll("\\d", "");
        System.out.println(s);
    }
}

四、StringBuilder 类

1、StringBuilder 介绍和构造方法

StringBuilder的作用 : 提高字符串的操作效率
            
StringBuilder的介绍 :
	1. 一个可变的字符序列
	2. StringBuilder是字符串缓冲区, 将其理解是容器, 这个容器可以存储任意数据类型, 但是只要进入到这个容器, 全部变成字符串.

StringBuilder的构造方法 :
	public StringBuilder() : 创建一个空白的字符串缓冲区(容器), 其初始容量为16个字符
	public StringBuilder(String str) : 创建一个字符串缓冲区(容器), 容器在创建好之后, 就会带有参数的内容
package com.itheima.stringbuilder;

public class StringBuilderDemo2 {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("abc");
        System.out.println(sb);
    }
}

2、StringBuiler 常用成员方法

StringBuilder常用成员方法 :
	1. public StringBuilder append(任意类型) : 添加数据, 并返回对象自己
	2. public StringBuilder reverse() : 将缓冲区中的内容, 进行反转
	3. public int length() : 返回长度
	4. public String toString() : 将缓冲区的内容, 以String字符串类型返回
package com.itheima.stringbuilder;

public class StringBuilderDemo3 {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();

        // 链式编程: 调用的方法, 返回的结果是对象, 就可以继续向下调用方法
        sb.append("红色").append("绿色").append("蓝色");
        System.out.println(sb); // 红色绿色蓝色

        sb.reverse();
        System.out.println(sb); // 色蓝色绿色红

        System.out.println(sb.length()); // 6

        // 情况: 我数据在StringBuilder当中, 我要调用的方法, StringBuilder没有, 但是String有
        // 解决: 转换为String, 再调用
        String[] sArr = sb.toString().split("色");
        for (int i = 0; i < sArr.length; i++) {
            System.out.println(sArr[i]);
        }
    }
}

3、String 和 StringBuilder 的拼接内存图

在这里插入图片描述
在这里插入图片描述

五、Object 类

1、toString 方法

public String toString() 返回该对象的字符串表示

	public String toString() {
	    return getClass().getName() + "@" + Integer.toHexString(hashCode());
	}
	
	getClass().getName() : 类名称, 全类名(包名 + 类名)
	Integer.toHexString() : 转十六进制
	hashCode() : 返回的是对象内存地址 + 哈希算法, 算出来的整数 (哈希值)
	
	-------------------------------------------------------
	
	细节: 使用打印语句, 打印对象名的时候, println方法, 源码层面, 会自动调用该对象的toString方法.
		 public static String valueOf(Object obj) {
		    return (obj == null) ? "null" : obj.toString();
		 }
package com.itheima.object.tostring;

import com.itheima.object.Student;

import java.util.ArrayList;

public class ToStringDemo {
    public static void main(String[] args) {
        A a = new A();
        System.out.println(a);
        System.out.println(a.toString());

        Student stu = new Student("张三",23);
        System.out.println(stu);

        ArrayList<String> list = new ArrayList<>();
        list.add("abc");
        list.add("abc");
        list.add("abc");

        System.out.println(list);
    }
}

class A {
    @Override
    public String toString() {
        return "大哥重写了toString方法";
    }
}

2、equals 方法

Object类中的equals方法 :
	public boolean equals(Object obj) : 对象之间进行比较, 返回true, 或者是false.
		public boolean equals(Object obj) {
		    return (this == obj);
		}
	
	结论: Object类中的equals方法, 默认比较的是对象内存地址
	        - 通常会重写equals方法, 让对象之间, 比较内容
package com.itheima.object.equals;

import com.itheima.object.Student;

import java.util.Objects;

public class EqualsDemo {
    public static void main(String[] args) {
        Student stu1 = new Student("张三", 23);
        Student stu2 = new Student("张三", 24);
        System.out.println(stu1.equals(stu2)); // false
    }
}

----------------------------------------------------
package com.itheima.object;

public class Student {
    private String name;
    private int age;

//    @Override
//    public boolean equals(Object obj) {
//        // this : stu1
//        // obj : stu2
//        if (obj instanceof Student) {
//            Student stu2 = (Student) obj;
//            return this.age == stu2.age && this.name.equals(stu2.name);
//        } else {
//            return false;
//        }
//    }
    
    @Override
    public boolean equals(Object o) {
        // this : stu1
        // o : stu2
        if (this == o) {
            // 两个对象做地址值的比较, 如果地址相同, 里面的内容肯定相同, 直接返回为true.
            return true;
        }
    
        // 代码要是能够走到这里, 代表地址肯定不相同
        // 代码要是能够走到这里, 代表stu1, 肯定不是null
        // stu1不是null, stu2是null, 就直接返回false
    
        // this.getClass() != o.getClass() : 两个对象的字节码是否相同
        // 如果字节码不相同, 就意味着类型不相同, 直接返回false
        if (o == null || this.getClass() != o.getClass()) {
            return false;
        }
    
        // 代码要是能够走到这里, 代表字节码相同, 类型肯定相同.
        // 向下转型
        Student student = (Student) o;
        // 比较
        return this.age == student.age && Objects.equals(this.name, student.name);
    }

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

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

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Student{name = " + name + ", age = " + age + "}";
    }
}

六、Objects 类

											// a : stu1
                           					// b : stu2
public static boolean equals(Object a, Object b) {

    -----------------------------------------------------------------------------------------------
    a == b : 如果地址相同, 就会返回为true, 这里使用的符号是短路 || , 左边为true, 右边就不执行了
			- 结论: 如果地址相同, 方法直接返回为true
               		如果地址不相同, 就会返回false, 短路 || , 左边为false, 右边要继续执行.

    -----------------------------------------------------------------------------------------------

    a != null : 假设 a 是 null 值
                            null != null  :  false
                            && : 左边为false, 右边不执行, 右边不执行, 记录着null值的a, 就不会调用equals方法
                                        - 避免空指针异常 !

    -----------------------------------------------------------------------------------------------

    a != null : 假设 a 不是 null 值
                            stu1 != null : true
                            && : 左边为true, 右边继续执行, a.equals(b), 这里就不会出现空指针异常

    return (a == b) || (a != null && a.equals(b));
}
package com.itheima.object.equals;

import com.itheima.object.Student;

import java.util.Objects;

public class EqualsDemo {
    public static void main(String[] args) {

        Student stu1 = null;
        Student stu2 = new Student("张三",23);

        System.out.println(Objects.isNull(stu1));
        System.out.println(Objects.isNull(stu2));

        // 问题: Objects.equals方法, 和 stu1.equals方法, 有什么区别?
        // 细节: Objects.equals方法, 内部依赖于我们自己所编写的equals
        // 好处: Objects.equals方法, 内部带有非null判断
        System.out.println(Objects.equals(stu1, stu2));
        System.out.println("看看我执行了吗?");
    }
}

七、Math 类

Math类 : 包含执行基本数字运算的方法
	public static int abs (int a) : 获取参数绝对值
	public static double ceil (double a) : 向上取整
	public static double floor (double a) : 向下取整
	public static int round (float a) : 四舍五入
	public static int max (int a, int b) : 获取两个int值中的较大值
	public static double pow (double a,double b) : 返回a的b次幂的值
	public static double random () : 返回值为double的随机值,范围[0.0,1.0)
package com.itheima.math;

public class MathDemo {
    public static void main(String[] args) {
        System.out.println(Math.abs(-123));         // 123
        System.out.println(Math.abs(-12.3));        // 12.3

        System.out.println("---------------------");
        System.out.println(Math.ceil(12.0));
        System.out.println(Math.ceil(12.2));
        System.out.println(Math.ceil(12.5));
        System.out.println(Math.ceil(12.9));

        System.out.println("---------------------");
        System.out.println(Math.floor(12.0));
        System.out.println(Math.floor(12.2));
        System.out.println(Math.floor(12.5));
        System.out.println(Math.floor(12.9));

        System.out.println("---------------------");
        System.out.println(Math.round(3.4)); // 3
        System.out.println(Math.round(3.6)); // 4

        System.out.println("---------------------");
        System.out.println(Math.max(10, 20)); // 20
        System.out.println(Math.min(10, 20)); // 10

        System.out.println("---------------------");
        System.out.println(Math.pow(2, 3)); // 8.0

        System.out.println("---------------------");
        System.out.println(Math.random());
    }
}

八、Random随机数

package com.itheima.random;

// 1. 找符咒
import java.util.Random;

public class RandomDemo {
    public static void main(String[] args) {
        // 2. 召唤精灵
        Random r = new Random();

        for (int i = 1; i <= 20; i++) {
            // 3. 指挥精灵产生随机数
            int num = r.nextInt(100) + 1;
            System.out.println(num);
        }

        System.out.println("-----------------------");

        // 需求: 产生20~80之间的随机数
        for (int i = 1; i <= 20; i++) {
            int num = r.nextInt(61) + 20;
            System.out.println(num);
        }
    }
}

九、System 类

System类常见方法 :
	1. public static void exit (int status) : 终止当前运行的 Java 虚拟机,非零表示异常终止
	2. public static long currentTimeMillis () : 返回当前系统的时间毫秒值形式
	                                                    - 返回1970年1月1日 0时0分0秒, 到现在所经历过的毫秒值
	3. public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) : 数组拷贝
	                                            src: 数据源数组
	                                            srcPos: 起始索引
	                                            dest: 目的地数组
	                                            destPos: 起始索引
	                                            length: 拷贝的个数
package com.itheima.system;

public class SystemDemo {
    public static void main(String[] args) {
        int[] arr = {11,22,33,44,55};
        int[] destArr = new int[3];

        System.arraycopy(arr, 2, destArr, 0, 3);

        for (int i = 0; i < destArr.length; i++) {
            System.out.println(destArr[i]);
        }
    }

    private static void method() {
        long start = System.currentTimeMillis();

        String s = "";
        for(int i = 1; i <= 100000; i++){
            s += i;
        }
        System.out.println(s);

        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}

十、BigDecimal 类

BigDecimal类 : 解决小数运算中, 出现的不精确问题

BigDecimal创建对象 :
   public BigDecimal(double val) : 不推荐, 无法保证小数运算的精确
   ---------------------------------------------------------------
   public BigDecimal(String val)
   public static BigDecimal valueOf(double val)

BigDecimal常用成员方法 :
   public BigDecimal add(BigDecimal b) : 加法
   public BigDecimal subtract(BigDecimal b) : 减法
   public BigDecimal multiply(BigDecimal b) : 乘法
   public BigDecimal divide(BigDecimal b) : 除法
   public BigDecimal divide (另一个BigDecimal对象,精确几位,舍入模式) : 除法

注意: 如果使用BigDecimal运算, 出现了除不尽的情况, 就会出现异常
package com.itheima.bigdecimal;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class BigDecimalDemo {
    public static void main(String[] args) {
        BigDecimal bd1 = BigDecimal.valueOf(10.0);
        BigDecimal bd2 = BigDecimal.valueOf(3.0);

        System.out.println(bd1.divide(bd2, 2, RoundingMode.HALF_UP)); // 3.33 四舍五入
        System.out.println(bd1.divide(bd2, 2, RoundingMode.UP)); // 3.34 进一法
        System.out.println(bd1.divide(bd2, 2, RoundingMode.DOWN)); // 3.33 去尾法

        BigDecimal result = bd1.divide(bd2, 2, RoundingMode.HALF_UP);

        double v = result.doubleValue();
        Math.abs(v);
    }

    private static void method() {
        BigDecimal bd1 = BigDecimal.valueOf(0.1);
        BigDecimal bd2 = BigDecimal.valueOf(0.2);

        System.out.println(bd1.add(bd2));
        System.out.println(bd1.subtract(bd2));
        System.out.println(bd1.multiply(bd2));
        System.out.println(bd1.divide(bd2));
    }
}

十一、包装类

1、Integer 包装类

包装类 : 将基本数据类型, 包装成类, 变成引用数据类型

手动装箱: 调用方法, 手动将基本数据类型, 包装成类
            1. public Integer(int value) : 通过构造方法 (不推荐)
            2. public static Integer valueOf(int i) : 通过静态方法

手动拆箱: 调用方法, 手动将包装类, 拆成(转换)基本数据类型
            1. public int intValue() : 以 int 类型返回该 Integer 的值

JDK5版本开始, 出现了自动拆装箱 :
        1. 自动装箱 : 可以将基本数据类型, 直接赋值给包装类的变量
        2. 自动拆箱 : 可以将包装类的数据, 直接赋值给基本数据类型变量

        结论: 基本数据类型, 和对应的包装类, 可以直接做运算了, 不需要操心转换的问题了

Integer 常用方法 :
    public static String toBinaryString (int i) : 转二进制
    public static String toOctalString (int i)  : 转八进制
    public static String toHexString (int i)   : 转十六进制
    public static int parseInt (String s)     : 将数字字符串, 转换为数字
package com.itheima.integer;

public class IntegerDemo {
    public static void main(String[] args) {
        int num = 10;

        // 手动拆箱装箱
        Integer i1 = Integer.valueOf(num);
        System.out.println(i1);

        int i = i1.intValue();
        System.out.println(i);

        // 自动拆箱装箱
        Integer i2 = num;
        int i3 = i2;

        method();
    }

    public static void method() {
        int num = 100;

        System.out.println(Integer.toBinaryString(num));
        System.out.println(Integer.toOctalString(num));
        System.out.println(Integer.toHexString(num));

        String s = "123";

        System.out.println(Integer.parseInt(s) + 100);        // 223
    }
}

---------------------------------------------------------------------
package com.itheima.integer;

public class IntegerTest {
    /*
        已知字符串 String s = "10,50,30,20,40";
        请将该字符串转换为整数并存入数组
        随后求出最大值打印在控制台
     */
    public static void main(String[] args) {
        String s = "10,50,30,20,40";

        // 1. 根据逗号做切割
        String[] sArr = s.split(",");

        // 2. 准备一个整数数组, 准备存储转换后的数字
        int[] nums = new int[sArr.length];

        // 3. 遍历字符串数组
        for (int i = 0; i < sArr.length; i++) {
            // sArr[i] : 每一个数字字符串
            // 4. 将数字字符串转换为整数, 并存入数组
            nums[i] = Integer.parseInt(sArr[i]);
        }

        // 5. 求最大值
        int max = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if(nums[i] > max){
                max = nums[i];
            }
        }

        System.out.println("最大值为:" + max);
    }
}

2、包装类面试题

看程序说结果, 并说明原因

自动装箱的时候, 如果装箱的数据范围, 是-128~127, ==号比较的结果就是true, 反之都是false

自动装箱的原理 : 自动帮我们调用了 Integer.valueOf(127);
   	// i = 127
	public static Integer valueOf(int i) {
	    if (i >= -128 && i <= 127) {
	        return IntegerCache.cache[255];
	    }
	    return new Integer(i);
	}

如果装箱的数据, 不在 -128 ~ 127 之间, 会重新创建新的对象
如果装箱的数据, 在 -128 ~ 127 之间, 不会创建新的对象, 而是从底层的数组中, 取出一个提前创建好的Integer对象, 返回
	- Integer类中, 底层存在一个长度为256个大小的数组, Integer[] cache
		在数组中, 存储了256个Integer对象, 分别是 -128 ~ 127
package com.itheima.integer;

public class InterView {
    public static void main(String[] args) {
        Integer i1 = 127;
        Integer i2 = 127;
        System.out.println(i1 == i2);       // true

        Integer i3 = 129;
        Integer i4 = 129;
        System.out.println(i3 == i4);       // false

        Long i11 = 129L;
        Long i22 = 129L;
        System.out.println(i11 == i22); // false
        System.out.println(i11.equals(i22)); // true
    }
}

十二、Arrays 工具类

Arrays类常用方法 :
	public static String toString (类型[] a) : 将数组元素拼接为带有格式的字符串
	public static boolean equals (类型[] a, 类型[] b) : 比较两个数组内容是否相同
	public static int binarySearch (int[] a, int key) : 查找元素在数组中的索引 (二分查找法: 保证数组的元素是排好序的)
	                                               - 如果查找的元素, 在数组中不存在: 返回 (-(插入点) - 1)
	public static void sort (类型[] a) : 对数组进行默认升序排序
	            TODO: 后面学完了红黑树, 回头对这个方法做补充
package com.itheima.arrays;

import java.util.Arrays;

public class ArraysDemo {
    public static void main(String[] args) {
        int[] arr1 = {11, 22, 33, 44, 55};
        int[] arr2 = {11, 22, 33, 44, 66};

        // 将数组元素拼接为带有格式的字符串
        System.out.println(Arrays.toString(arr1)); // [11, 22, 33, 44, 55]
        // 比较两个数组内容是否相同
        System.out.println(Arrays.equals(arr1, arr2)); // false

        // 查找元素在数组中的索引
        System.out.println(Arrays.binarySearch(arr1, 33)); // 2
        System.out.println(Arrays.binarySearch(arr1, 66)); // -6

        int[] nums = {22, 11, 55, 44, 33};
        System.out.println(Arrays.binarySearch(nums, 11));      // -1

        Arrays.sort(nums);
        System.out.println(Arrays.binarySearch(nums, 11));      // 0

        // 对数组进行默认升序排序
        Arrays.sort(nums);
        System.out.println(Arrays.toString(nums)); // [11, 22, 33, 44, 55]
    }
}

十三、Collections 集合工具类

Collections: 集合工具类
	Collections并不属于集合,是用来操作集合的工具类
	
	常用方法
	    public static <T> boolean addAll(Collection<? super T> c, T... elements)	给集合对象批量添加元素
	    public static void shuffle(List<?> list) 	打乱List集合元素的顺序
	    public static <T> int binarySearch (List<T> list,  T key)	以二分查找法查找元素
	    public static <T> void max/min(Collection<T> coll)	根据默认的自然排序获取最大/小值
	    public static <T> void swap(List<?> list, int i, int j)	交换集合中指定位置的元素
	    public static <T> void sort(List<T> list)	将集合中元素按照默认规则排序
	        注意:本方式不可以直接对自定义类型的List集合排序,除非自定义类型实现了比较规则Comparable接口
	    public static <T> void sort(List<T> list,Comparator<? super T> c)	将集合中元素按照指定规则排序
package com.heima.tools;

import com.heima.domain.Student;

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

public class CollectionsDemo {
    public static void main(String[] args) {

        // 批量添加
        ArrayList<String> list = new ArrayList<>();
        Collections.addAll(list, "a", "b", "c", "d");
        System.out.println(list); // [a, b, c, d]

        // 二分查找
        int c = Collections.binarySearch(list, "c");
        System.out.println(c); // 2

        // 洗牌
        Collections.shuffle(list);
        System.out.println(list); // [b, c, d, a]

        // 从集合中找最值,依赖于 CompareTo方法
        ArrayList<Integer> nums = new ArrayList<>();
        Collections.addAll(nums, 1, 2, 3, 4, 5, 6, 7);
        System.out.println(Collections.max(nums)); // 7
        System.out.println(Collections.min(nums)); // 1

        ArrayList<Student> stus = new ArrayList<>();
        Collections.addAll(stus, new Student("张三", 23), new Student("李四", 26), new Student("王五", 24));
        System.out.println(Collections.max(stus));
        System.out.println(stus); // [Student{name = 张三, age = 23}, Student{name = 李四, age = 26}, Student{name = 王五, age = 24}]

        // 对集合中的元素进行交换
        Collections.swap(stus, 1, 2);
        System.out.println(stus); // [Student{name = 张三, age = 23}, Student{name = 王五, age = 24}, Student{name = 李四, age = 26}]

        // sort: 对集合进行排序
        ArrayList<Integer> box = new ArrayList<>();
        Collections.addAll(box, 1, 5, 3, 4, 2);
        Collections.sort(box);
        System.out.println(box); // [1, 2, 3, 4, 5]
        Collections.sort(box, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        System.out.println(box); // [5, 4, 3, 2, 1]
    }
}

十四、时间API

1、JDK8(-)时间API

1)、Date 类

Date类 : 表示时间的类
	1. 构造方法 :
	    public Date() : 将当前时间, 封装为Date日期对象
	    public Date(long time) : 把时间毫秒值转换成Date日期对象
	
	2. 常见方法 :
	    public long getTime() : 返回从1970年1月1日 00:00:00走到此刻的总的毫秒数
	    public void setTime(long time) : 设置日期对象的时间为当前时间毫秒值对应的时间
package com.itheima.jdk7.date;

import java.util.Date;

public class DateDemo1 {
    public static void main(String[] args) {
        // 将当前时间, 封装为Date日期对象
        Date d1 = new Date();
        System.out.println(d1);

        // 把时间毫秒值转换成Date日期对象
        Date d2 = new Date(1000L);
        System.out.println(d2);

        System.out.println(d1.getTime());
        System.out.println(d2.getTime());

        System.out.println("----------------------");
        Date d3 = new Date();
        d3.setTime(0L);
        System.out.println(d3);
    }
}

2)、SimpleDateFormat 类

SimpleDateFormat类 : 用于日期格式化
	1. 构造方法 :
		public SimpleDateFormat() : 创建一个日期格式化对象, 使用 [默认模式]
		public SimpleDateFormat(String pattern) : 创建一个日期格式化对象, [手动指定模式]
	
	2. 常用方法 :
		public final String format(Date date) : 将日期对象, 转换为字符串
		public final Date parse(String source) : 将日期字符串, 解析为日期对象
package com.itheima.jdk7.format;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatDemo {
    public static void main(String[] args) throws ParseException {
        String today = "2023年2月4日";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");

        Date date = simpleDateFormat.parse(today);
        System.out.println(date); // Sat Feb 04 00:00:00 CST 2023
    }

    private static void method() {
        // 创建一个日期格式化对象, 使用 [默认模式]
        // SimpleDateFormat simpleDateFormat = new SimpleDateFormat();

        // 创建一个日期格式化对象, [手动指定模式]
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");

        // 创建Date对象, 封装此刻的时间
        Date date = new Date();

        // 将日期对象, 转换为字符串
        String result = simpleDateFormat.format(date);
        System.out.println(result); // 2023年10月14日
    }
}

3)、Calendar 类

Calendar : 代表的是系统此刻时间对应的日历,通过它可以单独获取、修改时间中的年、月、日、时、分、秒等。

1. 创建对象 :
	public static Calendar getInstance() : 获取当前时间的日历对象
2. 常用方法 :
	public int get(int field) : 取日历中的某个字段信息
		get方法的参数 : Calendar类中的静态常量
		     Calendar.YEAR : 获取年份信息
		     Calendar.MONTH : 月份是0~11, 记得做+1操作
		     Calendar.DAY_OF_MONTH : 获取日
		     Calendar.DAY_OF_WEEK : 获取星期, 获取星期的时候, 需要提前设计一个数组
		     Calendar.DAY_OF_YEAR : 获取一年中的第几天

	public void set(int field,int value) : 修改日历的某个字段信息
	public void add(int field,int amount) : 为某个字段增加/减少指定的值
	public final void setTime(Date date) : 将日期对象, 转换为Calendar对象
	public final Date getTime() : 拿到此刻的日期对象
package com.itheima.jdk7.calendar;

import java.util.Calendar;

public class CalendarDemo {
    public static void main(String[] args) {
        Calendar c = Calendar.getInstance();

        c.add(Calendar.YEAR, -1);

        System.out.println(c.get(Calendar.YEAR));
    }

    private static void setMethod() {
        Calendar c = Calendar.getInstance();

        c.set(Calendar.YEAR, 2022);
        c.set(2008,8,8);

        System.out.println(c.get(Calendar.YEAR));
    }

    private static void getMethod() {
        // Calendar c : 抽象类
        // Calendar.getInstance() : 获取的是子类对象
        // 1. 获取当前时间的日历对象
        Calendar c = Calendar.getInstance();

        // 2. 调用get方法, 获取指定字段的信息
        int year = c.get(Calendar.YEAR);
        System.out.println(year);

        // 注意Calendar类的月份是 0~11, 想要获取常规的月份, 需要对结果 + 1操作
        int month = c.get(Calendar.MONTH);
        System.out.println(month + 1);

        int day = c.get(Calendar.DAY_OF_MONTH);
        System.out.println(day);

        char[] weeks = {' ', '日', '一', '二', '三', '四', '五', '六'};
        //  0     1     2    3     4     5    6    7

        int weekIndex = c.get(Calendar.DAY_OF_WEEK);
        System.out.println(weeks[weekIndex]);

        int dayOfYear = c.get(Calendar.DAY_OF_YEAR);
        System.out.println(dayOfYear);
    }
}

2、JDK8(+)时间API

1)、日历类

LocalDate : 代表本地日期(年、月、日、星期)
LocalTime : 代表本地时间(时、分、秒、纳秒)
LocalDateTime : 代表本地日期、时间(年、月、日、星期、时、分、秒、纳秒)

对象的创建方式:
	1. now() : 当前时间
	2. of(...) : 设置时间

LocalDateTime 转换LocalDate, LocalTime
	1. toLocalDate()
	2. toLocalTime()
        
注意点:
    LocalDateTime 、LocalDate 、LocalTime 都是不可变的,调用修改的相关方法, 返回的都是新的对象
1.1、LocalDateTime 类
package com.itheima.jdk8.p1_local_date_time;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class LocalDateTimeDemo {
    public static void main(String[] args) {
        // 获取此刻的时间对象(日期 时间)
        LocalDateTime nowDateTime = LocalDateTime.now();
        System.out.println("今天是:" + nowDateTime);
        // 年
        System.out.println(nowDateTime.getYear());
        // 月
        System.out.println(nowDateTime.getMonthValue());
        // 日
        System.out.println(nowDateTime.getDayOfMonth());
        // 时
        System.out.println(nowDateTime.getHour());
        // 分
        System.out.println(nowDateTime.getMinute());
        // 秒
        System.out.println(nowDateTime.getSecond());
        // 纳秒
        System.out.println(nowDateTime.getNano());

        // 转换
        LocalDate localDate = nowDateTime.toLocalDate();
        LocalTime localTime = nowDateTime.toLocalTime();

        // 日 : 当年的第几天
        System.out.println("dayOfYear:" + nowDateTime.getDayOfYear());
        // 星期
        System.out.println("星期" + nowDateTime.getDayOfWeek());
        System.out.println("星期" + nowDateTime.getDayOfWeek().getValue());
        // 月份
        System.out.println("月份" + nowDateTime.getMonth());
        System.out.println("月份" + nowDateTime.getMonth().getValue());

        // 获取指定的时间对象
        LocalDateTime of = LocalDateTime.of(2008, 8, 8, 8, 8);
        System.out.println(of);
    }
}
1.2、LocalTime 类
package com.itheima.jdk8.p2_local_time;

import java.time.LocalTime;

public class LocalTimeDemo {
    public static void main(String[] args) {
        // 1、获取本地时间对象。
        LocalTime nowTime = LocalTime.now();
        // 今天的时间
        System.out.println("今天的时间:" + nowTime);

        // 时
        int hour = nowTime.getHour();
        System.out.println("hour:" + hour);

        // 分
        int minute = nowTime.getMinute();
        System.out.println("minute:" + minute);

        // 秒
        int second = nowTime.getSecond();
        System.out.println("second:" + second);

        // 纳秒
        int nano = nowTime.getNano();
        System.out.println("nano:" + nano);
    }
}
1.3、LocalDate 类
package com.itheima.jdk8.p3_local_date;

import java.time.LocalDate;

public class LocalDateDemo {
    public static void main(String[] args) {
        // 1、获取本地日期对象。
        LocalDate nowDate = LocalDate.now();
        System.out.println("今天的日期:" + nowDate);

        int year = nowDate.getYear();
        System.out.println("year:" + year);


        int month = nowDate.getMonthValue();
        System.out.println("month:" + month);

        int day = nowDate.getDayOfMonth();
        System.out.println("day:" + day);

        // 当年的第几天
        int dayOfYear = nowDate.getDayOfYear();
        System.out.println("dayOfYear:" + dayOfYear);

        // 星期
        System.out.println("星期:" + nowDate.getDayOfWeek());
        System.out.println("星期:" + nowDate.getDayOfWeek().getValue());

        // 月份
        System.out.println("月份:" +nowDate.getMonth());
        System.out.println("月份:" + nowDate.getMonth().getValue());
    }
}
1.4、修改方法
package com.itheima.jdk8.p4_update;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.MonthDay;

public class UpdateTimeDemo {
    public static void main(String[] args) {
        LocalDateTime nowTime = LocalDateTime.now();

        // 当前时间
        System.out.println(nowTime);
        // minus : 减去
        // minusYears(年), minusMonths(月), minusDays(日), minusWeeks(周), minusHours(时), minusMinutes(分), minusSeconds(秒), minusNanos(纳秒)
        System.out.println("减一小时:" + nowTime.minusHours(1));
        System.out.println("减一分钟:" +nowTime.minusMinutes(1));
        System.out.println("减一秒钟:" +nowTime.minusSeconds(1));
        System.out.println("减一纳秒:" +nowTime.minusNanos(1));

        System.out.println("对比时间, 确定方法返回的都是新的实例 >>>>>> " +nowTime);

        System.out.println("----------------");

        // plus : 加
        // plusYears(年), plusMonths(月), plusDays(日), plusWeeks(周), plusHours(时), plusMinutes(分), plusSeconds(秒), plusNanos(纳秒)
        System.out.println("加一小时:" + nowTime.plusHours(1));
        System.out.println("加一分钟:" + nowTime.plusMinutes(1));
        System.out.println("加一秒钟:" + nowTime.plusSeconds(1));
        System.out.println("加一纳秒:" + nowTime.plusNanos(1));

        System.out.println("---------------");

        // with : 这里体现出的是,设置效果
        System.out.println("修改的效果:");
        //withYear(年), withMonth(月), withDayOfMonth(日), withHour(时), withMinute(分), withSecond(秒), withNano(纳秒)
        System.out.println(nowTime.withYear(2008));
        System.out.println(nowTime.withMonth(8));
        System.out.println(nowTime.withDayOfMonth(8));
        System.out.println(nowTime.withHour(8));
        System.out.println(nowTime.withMinute(8));
        System.out.println(nowTime.withSecond(8));
        System.out.println(nowTime.withNano(8));
        System.out.println("---------------");

        LocalDate myDate = LocalDate.of(2008, 8, 8);
        LocalDate nowDate = LocalDate.now();

        //2008-08-08是否在nowDate之前?
        System.out.println(myDate + "是否在" + nowDate + "之前? " + myDate.isBefore(nowDate)); // true

        //2008-08-08是否在nowDate之后?
        System.out.println(myDate + "是否在" + nowDate + "之后? " + myDate.isAfter(nowDate)); // false
        System.out.println("---------------------------");

        // 判断两个时间是否相同
        System.out.println(myDate.equals(nowDate)); // false
    }
}

2)、日期格式化类

2.1、DateTimeFormatter 类
用于时间的格式化和解析:

1. 对象的获取 :
	static DateTimeFormatter ofPattern(格式) : 获取格式对象

2. 格式化 :
	String format(时间对象) : 按照指定方式格式化

3. 解析 :
	LocalDateTime.parse("解析字符串", 格式化对象);
	LocalDate.parse("解析字符串", 格式化对象);
	LocalTime.parse("解析字符串", 格式化对象);
package com.itheima.jdk8.p5_date_time_formatter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterDemo {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println("格式化之前:" + now); // 2023-06-13T21:56:23.341793700

        // 获取格式化对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");

        // 格式化
        String result = formatter.format(now);
        System.out.println("格式化之后:" + result); // 2023年6月13日

        // 解析
        String time = "2008年08月08日";
        LocalDate parse = LocalDate.parse(time, formatter);
        System.out.println(parse); // 2008-08-08
    }
}

3)、时间类

3.1、Instant 类
Instant类 : 用于表示时间的对象,  类似之前所学习的Date

Instant类常见方法 :
	static Instant now() : 获取当前时间的Instant对象(标准时间)
	static Instant ofXxxx(long epochMilli) : 根据(秒/毫秒/纳秒)获取Instant对象
	ZonedDateTime atZone(ZoneId zone) : 指定时区
	boolean isXxx(Instant otherInstant) : 判断系列的方法
	Instant minusXxx(long millisToSubtract) : 减少时间系列的方法
	Instant plusXxx(long millisToSubtract) : 增加时间系列的方法
package com.itheima.jdk8.p6_instant;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class InstantDemo2 {
    public static void main(String[] args) {
        // 获取当前时间的Instant对象(标准时间)
        Instant now = Instant.now();
        System.out.println("当前时间为(世界标准时间):" + now);
        System.out.println("------------------");

        // 根据(秒/毫秒/纳秒)获取Instant对象
        Instant instant1 = Instant.ofEpochMilli(1000);
        Instant instant2 = Instant.ofEpochSecond(5);

        System.out.println(instant1); // 1970-01-01T00:00:01Z
        System.out.println(instant2); // 1970-01-01T00:00:05Z
        System.out.println("------------------");

        // 指定时区
        ZonedDateTime zonedDateTime = Instant.now().atZone(ZoneId.systemDefault());
        System.out.println("带时区的时间:" + zonedDateTime); // 2023-10-14T11:35:14.284344300+08:00[Asia/Shanghai]
        System.out.println("------------------");

        // 判断系列的方法
        System.out.println(now.isBefore(instant1)); // false
        System.out.println(now.isAfter(instant1)); // true
        System.out.println("------------------");

        // 减少时间系列的方法
        System.out.println("减1000毫秒:" + now.minusMillis(1000));
        System.out.println("减5秒钟:" + now.minusSeconds(5));
        System.out.println("------------------");

        // 增加时间系列的方法
        System.out.println("加1000毫秒:" + now.plusMillis(1000));
        System.out.println("加5秒钟:" + now.plusSeconds(5));
        System.out.println("------------------");
    }
}
3.2、ZoneId 类
ZoneId类 : 时区类

常见方法 :
	1. static Set<String> getAvailableZoneIds() : 获取Java中支持的所有时区
	2. static ZoneId systemDefault() : 获取系统默认时区
	3. static ZoneId of(String zoneId) : 获取一个指定时区
package com.itheima.jdk8.p7_Zone;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Set;

public class ZoneIdDemo {
    public static void main(String[] args) {
        // 获取Java中支持的所有时区
        Set<String> set = ZoneId.getAvailableZoneIds();
        System.out.println(set);
        System.out.println(set.size()); // 600
        System.out.println("-----------------------");

        // 获取系统默认时区
        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println(zoneId); // Asia/Shanghai
        System.out.println("-----------------------");

        // 获取一个指定时区
        ZoneId of = ZoneId.of("Africa/Nairobi");
        System.out.println(of); // Africa/Nairobi

        ZonedDateTime zonedDateTime = Instant.now().atZone(of);
        System.out.println(zonedDateTime); // 2023-06-13T17:04:04.213260400+03:00[Africa/Nairobi]
    }
}
3.3、ZonedDateTime 类
ZoneDataTime 带时区的时间对象 :
	static ZonedDateTime now() : 获取当前时间的ZonedDateTime对象
	static ZonedDateTime ofXxxx(...) : 获取指定时间的ZonedDateTime对象
	ZonedDateTime withXxx(时间) : 修改时间系列的方法
	ZonedDateTime minusXxx(时间) : 减少时间系列的方法
	ZonedDateTime plusXxx(时间)  : 增加时间系列的方法
package com.itheima.jdk8.p7_Zone;

import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ZoneDateTimeDemo {
    public static void main(String[] args) {
        // 获取当前时间的ZonedDateTime对象
        ZonedDateTime now = ZonedDateTime.now();
        System.out.println(now); // 2023-10-14T11:39:39.130801900+08:00[Asia/Shanghai]
        System.out.println("--------------------------");

        // 获取指定时间的ZonedDateTime对象
        ZonedDateTime of = ZonedDateTime.of(
                2008, 8, 8, 8, 8, 8, 8, 
                ZoneId.systemDefault()
        );
        System.out.println(of);
        System.out.println("--------------------------");

        // 修改时间系列的方法
        System.out.println(now.withYear(2008));
        System.out.println(now.withMonth(8));
        System.out.println(now.withDayOfMonth(8));
        System.out.println("--------------------------");

        // 减少时间系列的方法
        System.out.println(now.minusYears(1));
        System.out.println(now.minusMonths(1));
        System.out.println(now.minusDays(1));
        System.out.println("--------------------------");

        // 增加时间系列的方法
        System.out.println(now.plusYears(1));
        System.out.println(now.plusMonths(1));
        System.out.println(now.plusDays(1));
    }
}

4)、工具类

4.1、Period 类
package com.itheima.jdk8.p8_interval;

import java.time.LocalDate;
import java.time.Period;

/**
 * Period计算日期间隔 (年月日)
 */
public class PeriodDemo {
    public static void main(String[] args) {
        // 此刻年月日
        LocalDate today = LocalDate.now();
        System.out.println(today);

        // 昨天年月日
        LocalDate otherDate = LocalDate.of(2023, 2, 4);
        System.out.println(otherDate);

        //Period对象表示时间的间隔对象
        Period period = Period.between(today, otherDate);    // 第二个参数减第一个参数

        System.out.println(period.getYears());      // 间隔多少年
        System.out.println(period.getMonths());     // 间隔的月份
        System.out.println(period.getDays());       // 间隔的天数
        System.out.println(period.toTotalMonths()); // 总月份
    }
}
4.2、Duration 类
package com.itheima.jdk8.p8_interval;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * Duration计算日期间隔 (时分秒)
 */
public class DurationDemo {
    public static void main(String[] args) {
        // 此刻日期时间对象
        LocalDateTime today = LocalDateTime.now();
        System.out.println(today);

        // 昨天的日期时间对象
        LocalDateTime otherDate = LocalDateTime.of(2023, 2
                , 4, 0, 0, 0);

        System.out.println(otherDate);

        Duration duration = Duration.between(otherDate, today); // 第二个参数减第一个参数

        System.out.println(duration.toDays());                  // 两个时间差的天数
        System.out.println(duration.toHours());                 // 两个时间差的小时数
        System.out.println(duration.toMinutes());               // 两个时间差的分钟数
        System.out.println(duration.toMillis());                // 两个时间差的毫秒数
        System.out.println(duration.toNanos());                 // 两个时间差的纳秒数
    }
}
4.3、ChronoUnit 类
package com.itheima.jdk8.p8_interval;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * ChronoUnit可用于在单个时间单位内测量一段时间,这个工具类是最全的了,可以用于比较所有的时间单位
 */
public class ChronoUnitDemo {
    public static void main(String[] args) {
        // 本地日期时间对象:此刻的
        LocalDateTime today = LocalDateTime.now();
        System.out.println(today);

        // 生日时间
        LocalDateTime birthDate = LocalDateTime.of(2023, 2, 4,
                0, 0, 0);
        System.out.println(birthDate);

        System.out.println("相差的年数:" + ChronoUnit.YEARS.between(birthDate, today));
        System.out.println("相差的月数:" + ChronoUnit.MONTHS.between(birthDate, today));
        System.out.println("相差的周数:" + ChronoUnit.WEEKS.between(birthDate, today));
        System.out.println("相差的天数:" + ChronoUnit.DAYS.between(birthDate, today));
        System.out.println("相差的时数:" + ChronoUnit.HOURS.between(birthDate, today));
        System.out.println("相差的分数:" + ChronoUnit.MINUTES.between(birthDate, today));
        System.out.println("相差的秒数:" + ChronoUnit.SECONDS.between(birthDate, today));
        System.out.println("相差的毫秒数:" + ChronoUnit.MILLIS.between(birthDate, today));
        System.out.println("相差的微秒数:" + ChronoUnit.MICROS.between(birthDate, today));
        System.out.println("相差的纳秒数:" + ChronoUnit.NANOS.between(birthDate, today));
        System.out.println("相差的半天数:" + ChronoUnit.HALF_DAYS.between(birthDate, today));
        System.out.println("相差的十年数:" + ChronoUnit.DECADES.between(birthDate, today));
        System.out.println("相差的世纪(百年)数:" + ChronoUnit.CENTURIES.between(birthDate, today));
        System.out.println("相差的千年数:" + ChronoUnit.MILLENNIA.between(birthDate, today));
        System.out.println("相差的纪元数:" + ChronoUnit.ERAS.between(birthDate, today));
    }
}

5)、案例

package com.itheima.test;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;

public class CalculateAgeTest {
    /*
        需求 : 键盘录入用户生日, 计算出用户的实际年龄.
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入您的生日: ");
        String birthday = sc.nextLine();

        // 1. 将键盘录入的日期字符串, 转换为日期对象 (生日那一天的)
        LocalDate birthdayDate = LocalDate.parse(birthday, DateTimeFormatter.ofPattern("yyyy年M月d日"));

        // 2. 获取今天的日期对象
        LocalDate now = LocalDate.now();

        // 3. 计算时间间隔
        long result = ChronoUnit.YEARS.between(birthdayDate, now);

        System.out.println(result);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值