11.常用类

常用类

包装类

Java为八大基本类型都提供了一个包装类(java中不能定义基本类型对象),这样就可以把基本类型转换成对象来处理了。

image-20211124180111803

image-20211124180257487

image-20211124180303916

黄色的表示该包装类继承了Number类,而Boolean和Character这没有继承Number类。当某个类实现了Comparable接口之后,表示该类可以进行比较。而包装类都实现了Comparable接口,表示包装类都可以进行比较。

包装类和基本数据的转换,这里以int和Integer演示

public class Integer01 {
    public static void main(String[] args) {
        //演示int <--> Integer 的装箱和拆箱
        //jdk5前是手动装箱和拆箱
        //手动装箱 int->Integer,下面是手动装箱的两种方式
        int n1 = 100;
        Integer integer = new Integer(n1);
        Integer integer1 = Integer.valueOf(n1);

        //手动拆箱
        //Integer -> int
        int i = integer.intValue();

        //jdk5后,就可以自动装箱和自动拆箱
        int n2 = 200;
        //自动装箱 int->Integer
        Integer integer2 = n2; //底层使用的是 Integer.valueOf(n2)
        //自动拆箱 Integer->int
        int n3 = integer2; //底层仍然使用的是 intValue()方法
    }
}

包装类和String类型的相互转换,以Integer和String转换为例

public class WrapperVSString {
    public static void main(String[] args) {
        //包装类(Integer)->String
        Integer i = 100;//自动装箱
        //方式1
        String str1 = i + "";
        //方式2
        String str2 = i.toString();
        //方式3
        String str3 = String.valueOf(i);

        //String -> 包装类(Integer)
        String str4 = "12345";
        Integer i2 = Integer.parseInt(str4);//使用到自动装箱
        Integer i3 = new Integer(str4);//构造器
    }
}

Integer类和Character类的常用方法

public class WrapperMethod {
    public static void main(String[] args) {
        System.out.println(Integer.MIN_VALUE); //返回最小值
        System.out.println(Integer.MAX_VALUE);//返回最大值

        System.out.println(Character.isDigit('a'));//判断是不是数字
        System.out.println(Character.isLetter('a'));//判断是不是字母
        System.out.println(Character.isUpperCase('a'));//判断是不是大写
        System.out.println(Character.isLowerCase('a'));//判断是不是小写

        System.out.println(Character.isWhitespace('a'));//判断是不是空格
        System.out.println(Character.toUpperCase('a'));//转成大写
        System.out.println(Character.toLowerCase('A'));//转成小写

    }
}

String类

概念

  1. 宇符串的字符使用Unicode字符编码,一个字符(不区分字母还是汉字)占两个字节。
  2. String类较常用构造器(其它看手册):
    String s1 = new String();
    String s2 = new String(String original);
    String s3 = new String(char[] a);
    String s4 = new String(char[] a,int startIndex, int count)
  3. .String 类实现了接口 Serializable【表示String类可以串行化:可以在网络传输】
  4. String类实现了接口 Comparable 【表示String类对象可以比较大小】
  5. String 是 final 类,不能被其他的类继承。
  6. String 有属性 private final char value[]; 用于存放字符串内容
  7. 一定要注意:value 是一个 final 类型, 不可以修改(需要功力):即 value 不能指向新的地址,但是单个字符内容是可以变化的。

创建String对象的两种方式

  1. 直接赋值 String s1 =“test”;
  2. 调用构造器 String s2 = new String(“test”);
区别
方式一

先从常量池查看是否有"test”数据空间,如果有,直接指向;如果
没有则在常量池中创建,然后指向。s1最终指向的是常量池的空间地址。

方式二

先在堆中创建空间,里面维护了value属性,指向常量池的test空间。如果常量池没有"test",则在常量池中创建,如果有,直接通过value指向。s2最终指向的是堆中的空间地址。而value指向的才是常量池的地址。

内存分布图

image-20211126133132291

String类的常用方法

image-20211126134948925

public class StringMethod01 {
    public static void main(String[] args) {
        //1. equals 前面已经讲过了. 比较内容是否相同,区分大小写
        String str1 = "hello";
        String str2 = "Hello";
        System.out.println(str1.equals(str2));

        // 2.equalsIgnoreCase 忽略大小写的判断内容是否相等
        String username = "johN";
        if ("john".equalsIgnoreCase(username)) {
            System.out.println("Success!");
        } else {
            System.out.println("Failure!");
        }
        // 3.length 获取字符的个数,字符串的长度
        System.out.println("韩顺平".length());
        
        // 4.indexOf 获取字符在字符串对象中第一次出现的索引,索引从0开始,如果找不到,返回-1
        String s1 = "wer@terwe@g";
        int index = s1.indexOf('@');
        System.out.println(index);// 3
        System.out.println("weIndex=" + s1.indexOf("we"));//0
        
        // 5.lastIndexOf 获取字符在字符串中最后一次出现的索引,索引从0开始,如果找不到,返回-1
        s1 = "wer@terwe@g@";
        index = s1.lastIndexOf('@');
        System.out.println(index);//11
        System.out.println("ter的位置=" + s1.lastIndexOf("ter"));//4
        
        // 6.substring 截取指定范围的子串
        String name = "hello,张三";
        //下面name.substring(6) 从索引6开始截取后面所有的内容
        System.out.println(name.substring(6));//截取后面的字符
        //name.substring(0,5)表示从索引0开始截取,截取到索引 5-1=4位置
        System.out.println(name.substring(2,5));//llo

    }

image-20211126135051573

public class StringMethod02 {
    public static void main(String[] args) {
        // 1.toUpperCase转换成大写
        String s = "heLLo";
        System.out.println(s.toUpperCase());//HELLO

        // 2.toLowerCase
        System.out.println(s.toLowerCase());//hello

        // 3.concat拼接字符串
        String s1 = "宝玉";
        s1 = s1.concat("林黛玉").concat("薛宝钗").concat("together");
        System.out.println(s1);//宝玉林黛玉薛宝钗together

        // 4.replace 替换字符串中的字符
        s1 = "宝玉 and 林黛玉 林黛玉 林黛玉";
        //在s1中,将 所有的 宝玉 替换成 jack
        // 老韩解读: s1.replace() 方法执行后,返回的结果才是替换过的.对s1没有任何影响
        String s11 = s1.replace("宝玉", "jack");
        System.out.println(s1);//宝玉 and 林黛玉 林黛玉 林黛玉
        System.out.println(s11);//jack and 林黛玉 林黛玉 林黛玉
        
        // 5.split 分割字符串, 对于某些分割字符,我们需要 转义比如 | \\等
        String poem = "E:\\aaa\\bbb";
        String[] split = poem.split("\\\\");
        System.out.println("==分割后内容===");
        for (int i = 0; i < split.length; i++) {
            System.out.println(split[i]);
        }
        
        // 6.toCharArray 转换成字符数组
        s = "happy";
        char[] chs = s.toCharArray();
        for (int i = 0; i < chs.length; i++) {
            System.out.println(chs[i]);
        }
        
        // 7.compareTo 比较两个字符串的大小,如果前者大,
        // 则返回正数,后者大,则返回负数,如果相等,返回0
        // 老韩解读
        // (1) 如果长度相同,并且每个字符也相同,就返回 0
        // (2) 如果长度相同,字符不同,就返回c1 - c2
        // (3) 如果前面的部分都相同,就返回 str1.len - str2.len
        String a = "jcck";
        String b = "jack";
        System.out.println(a.compareTo(b)); // 返回值是 'c' - 'a' = 2的值
        
        // 8.format 格式字符串
        /* 占位符有:
         * %s 字符串 %c 字符 %d 整型 %.2f 浮点型
         *
         */
        String name = "john";
        int age = 10;
        double score = 56.857;
        char gender = '男';
        //将所有的信息都拼接在一个字符串.
        String info =
                "我的姓名是" + name + "年龄是" + age + ",成绩是" + score + "性别是" + gender + "。希望大家喜欢我!";

        System.out.println(info);


        //老韩解读
        //1. %s , %d , %.2f %c 称为占位符
        //2. 这些占位符由后面变量来替换
        //3. %s 表示后面由 字符串来替换
        //4. %d 是整数来替换
        //5. %.2f 表示使用小数来替换,替换后,只会保留小数点两位, 并且进行四舍五入的处理
        //6. %c 使用char 类型来替换
        String formatStr = "我的姓名是%s 年龄是%d,成绩是%.2f 性别是%c.希望大家喜欢我!";

        String info2 = String.format(formatStr, name, age, score, gender);

        System.out.println("info2=" + info2);
    }

“abc”.intern();//返回的是该字符串在常量池中的地址,如果不存在,则在常量池中创建一个。

练习题

//创建了几个对象?
String a = "hello" + "abc"; 
//创建了一个对象,编译器有优化;等价于String a = "helloabc";
public class String02 {
    public static void main(String[] args) {

        String a = "hello";
        String b = "abc";
        String c = a + b;// 在常量池中创建了几个对象?一共在常量池中创建了3个对象
        
        //底层执行
        //1. StringBuilder sb =new StringBuilder();
        //2. sb.append("hello");
        //3. sb.append("abc");
        //4. 最后sb.toString();返回一个String对象 new String(value,0,count),其中value一个字符数组,count是value的个数
    }
}

字符串拼接使用String的 “+”还是StringBuilder

StringBuffer

概念

  1. StringBuffer代表可变的字符序列,可以对字符串内容进行增删。
  2. 很多方法与String相同,但StringBuffer是可变长度的。
  3. StringBuffer 的直接父类 是 AbstractStringBuilder,在父类中 AbstractStringBuilder 有属性 char[] value,不是 final,即表示该value数组存放字符串内容,引出该字符串是存放在堆中的 ,并不是存放在常量池中。
  4. StringBuffer 实现了 Serializable, 即 StringBuffer 的对象可以串行化,即可以在网络中进行传输。
  5. StringBuffer 是一个 final 类,不能被继承。
  6. . 因为 StringBuffer 字符内容是存在 char[] value, 所以在变化(增加/删除) ,不用每次都更换地址(即不是每次创建新对象), 所以效率高于 String.

String和StringBuffer的不同点

  1. String保存的是字符串常量,里面的值不能更改,每次String类的更新实际上就是更改地址,效率较低 //private final char value[]----这个是指向常量池中的地址
    2)String Buffer保存的是字符串变量,里面的值可以更改,每次
    StringBuffer的更新实际上可以更新内容,不用每次更新地址,效率较高//char[] value-----这个放在堆。

String和StringBuffer相互转换

    public static void main(String[] args) {

        //看 String——>StringBuffer
        String str = "hello tom";
        //方式1 使用构造器
        StringBuffer stringBuffer = new StringBuffer(str);
        
        //方式2 使用的是append方法
        StringBuffer stringBuffer1 = new StringBuffer();
        stringBuffer1 = stringBuffer1.append(str);

        
        //看看 StringBuffer ->String
        StringBuffer stringBuffer3 = new StringBuffer("韩顺平教育");
        //方式1 使用StringBuffer提供的 toString方法
        String s = stringBuffer3.toString();
        
        //方式2: 使用构造器来搞定
        String s1 = new String(stringBuffer3);
    }

StringBuilder

StringBuilder和StringBuffer几乎一样,不同点就是StringBuilder不是线程安全的,而StringBuffer是线程安全的,因为StringBuilder不是线程安全的,所有StringBuilder在某些情况下要比StringBuffer块

StringBuffer和StringBuilder的常用方法(这里以StringBuffer来演示)

    public static void main(String[] args) {

        StringBuffer s = new StringBuffer("hello");
        
        
        //增
        s.append(',');// "hello,"
        s.append("张三丰");//"hello,张三丰"
        s.append("赵敏").append(100).append(true).append(10.5);//"hello,张三丰赵敏100true10.5"
        System.out.println(s);//"hello,张三丰赵敏100true10.5"


        //删
        /*
         * 删除索引为>=start && <end 处的字符
         * 解读: 删除 11~14的字符 [11, 14)
         */
        s.delete(11, 14);
        System.out.println(s);//"hello,张三丰赵敏true10.5"
        
        
        //改
        //老韩解读,使用 周芷若 替换 索引9-11的字符 [9,11)
        s.replace(9, 11, "周芷若");
        System.out.println(s);//"hello,张三丰周芷若true10.5"
        
      
        //查
        //查找指定的子串在字符串第一次出现的索引,如果找不到返回-1
        int indexOf = s.indexOf("张三丰");
        System.out.println(indexOf);//6
        
        
        //插
        //老韩解读,在索引为9的位置插入 "赵敏",原来索引为9的内容自动后移
        s.insert(9, "赵敏");
        System.out.println(s);//"hello,张三丰赵敏周芷若true10.5"
        //长度
        System.out.println(s.length());//22
        System.out.println(s);
    }

String、StringBuffer和StringBuilder的比较

image-20211126164217522

String、StringBuffer和StringBuilder的选择

image-20211127155057877

Math类

常用方法

image-20211126210856246

public class MathMethod {
    public static void main(String[] args) {
        //看看Math常用的方法(静态方法)
        //1.abs 绝对值
        int abs = Math.abs(-9);
        System.out.println(abs);//9
        
        //2.pow 求幂
        double pow = Math.pow(2, 4);//2的4次方
        System.out.println(pow);//16
        
        //3.ceil 向上取整,返回>=该参数的最小整数(转成double);
        double ceil = Math.ceil(3.9);
        System.out.println(ceil);//4.0
        
        //4.floor 向下取整,返回<=该参数的最大整数(转成double)
        double floor = Math.floor(4.001);
        System.out.println(floor);//4.0
        
        //5.round 四舍五入  Math.floor(该参数+0.5)
        long round = Math.round(5.51);
        System.out.println(round);//6
        
        //6.sqrt 求开方
        double sqrt = Math.sqrt(9.0);
        System.out.println(sqrt);//3.0

        //7.random 求随机数
        //  random 返回的是 0 <= x < 1 之间的一个随机小数
        
        // 思考:请写出获取 a-b之间的一个随机整数,a,b均为整数 ,比如 a = 2, b=7
        //  即返回一个数 x  2 <= x <= 7
        // 老韩解读 Math.random() * (b-a) 返回的就是 0  <= 数 <= b-a
        // (1) (int)(a) <= x <= (int)(a + Math.random() * (b-a +1) )
        // (2) 使用具体的数给小伙伴介绍 a = 2  b = 7
        //  (int)(a + Math.random() * (b-a +1) ) = (int)( 2 + Math.random()*6)
        //  Math.random()*6 返回的是 0 <= x < 6 小数
        //  2 + Math.random()*6 返回的就是 2<= x < 8 小数
        //  (int)(2 + Math.random()*6) = 2 <= x <= 7
        // (3) 公式就是  (int)(a + Math.random() * (b-a +1) )
        for(int i = 0; i < 100; i++) {
            System.out.println((int)(2 +  Math.random() * (7 - 2 + 1)));
        }

        //max , min 返回最大值和最小值
        int min = Math.min(1, 9);
        int max = Math.max(45, 90);
        System.out.println("min=" + min);
        System.out.println("max=" + max);

    }

Arrays类

常用方法

  1. String toStirng() 返回数组的字符串形式

  2. sort排序

    1. 自然排序

    2. 定制排序

      public class ArraysSortCustom {
          public static void main(String[] args) {
      
              int[] arr = {1, -1, 8, 0, 20};
              //bubble01(arr);
      
              bubble02(arr, new Comparator() {
                  @Override
                  public int compare(Object o1, Object o2) {
                      int i1 = (Integer) o1;
                      int i2 = (Integer) o2;
                      return i2 - i1;// return i2 - i1;从大到小排序
                  }
              });
      
              System.out.println("==定制排序后的情况==");
              System.out.println(Arrays.toString(arr));
      
          }
      
          //使用冒泡完成排序
          public static void bubble01(int[] arr) {
              int temp = 0;
              for (int i = 0; i < arr.length - 1; i++) {
                  for (int j = 0; j < arr.length - 1 - i; j++) {
                      //从小到大
                      if (arr[j] > arr[j + 1]) {
                          temp = arr[j];
                          arr[j] = arr[j + 1];
                          arr[j + 1] = temp;
                      }
                  }
              }
          }
      
          //结合冒泡 + 定制
          public static void bubble02(int[] arr, Comparator c) {
              int temp = 0;
              for (int i = 0; i < arr.length - 1; i++) {
                  for (int j = 0; j < arr.length - 1 - i; j++) {
                      //数组排序由 c.compare(arr[j], arr[j + 1])返回的值决定
                      if (c.compare(arr[j], arr[j + 1]) > 0) {
                          temp = arr[j];
                          arr[j] = arr[j + 1];
                          arr[j + 1] = temp;
                      }
                  }
              }
          }
      }
      
  3. int binarySearch(数组,搜索条件) 通过二分搜索法进行查找,要求必须排好序。返回搜索到的下标。

  4. copyOf(数组,复制的数组个数) 数组元素的复制,注:这个也有定制化方法

  5. fill() 数组元素的填充

    1. Integer[] num = new Integer[]{9,3,2};
      Arrays.fill(num,99);
      //那么num里面的值就全部变成99;我认为这个在数组初始化的时候比较好用。
      
  6. boolean equals(数组1,数组2) 比较两个数组元素内容是否完全一致

  7. asList 将一组值,转换为List

  8. split() 根据某些条件可以分割字符串。split("")表示将字符串转换成String数组,按照单个字符分割

  9. toChartArray();将字符串转换成字符数组,按照单个字符分割

public class ArraysMethod02 {
    public static void main(String[] args) {
        Integer[] arr = {1, 2, 90, 123, 567};
        // binarySearch 通过二分搜索法进行查找,要求必须排好
        //1. 使用 binarySearch 二叉查找
        //2. 要求该数组是有序的. 如果该数组是无序的,不能使用binarySearch
        //3. 如果数组中不存在该元素,就返回 return -(low + 1);  // key not found.
        int index = Arrays.binarySearch(arr, 567);
        System.out.println("index=" + index);

        //copyOf 数组元素的复制
        //1. 从 arr 数组中,拷贝 arr.length个元素到 newArr数组中
        //2. 如果拷贝的长度 > arr.length 就在新数组的后面 增加 null
        //3. 如果拷贝长度 < 0 就抛出异常NegativeArraySizeException
        //4. 该方法的底层使用的是 System.arraycopy()
        Integer[] newArr = Arrays.copyOf(arr, arr.length);
        System.out.println("==拷贝执行完毕后==");
        System.out.println(Arrays.toString(newArr));

        //ill 数组元素的填充
        Integer[] num = new Integer[]{9,3,2};
        //1. 使用 99 去填充 num数组,可以理解成是替换原理的元素
        Arrays.fill(num, 99);
        System.out.println("==num数组填充后==");
        System.out.println(Arrays.toString(num));

        //equals 比较两个数组元素内容是否完全一致
        Integer[] arr2 = {1, 2, 90, 123};
        //1. 如果arr 和 arr2 数组的元素一样,则方法true;
        //2. 如果不是完全一样,就返回 false
        boolean equals = Arrays.equals(arr, arr2);
        System.out.println("equals=" + equals);

        //asList 将一组值,转换成list
        //1. asList方法,会将 (2,3,4,5,6,1)数据转成一个List集合
        //2. 返回的 asList 编译类型 List(接口)
        //3. asList 运行类型 java.util.Arrays#ArrayList, 是Arrays类的
        //   静态内部类 private static class ArrayList<E> extends AbstractList<E>
        //              implements RandomAccess, java.io.Serializable
        List asList = Arrays.asList(2,3,4,5,6,1);
        System.out.println("asList=" + asList);
        System.out.println("asList的运行类型" + asList.getClass());
    }

System类

image-20211127140818631

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

        //exit 退出当前程序

//        System.out.println("ok1");
//        //1. exit(0) 表示程序退出
//        //2. 0 表示一个状态 , 正常的状态
//        System.exit(0);//
//        System.out.println("ok2");

        //arraycopy :复制数组元素,比较适合底层调用,
        // 一般使用Arrays.copyOf完成复制数组

        int[] src={1,2,3};
        int[] dest = new int[3];// dest 当前是 {0,0,0}

        //1. 主要是搞清楚这五个参数的含义
        //2.
        //     源数组
        //     * @param      src      the source array.
        //     srcPos: 从源数组的哪个索引位置开始拷贝
        //     * @param      srcPos   starting position in the source array.
        //     dest : 目标数组,即把源数组的数据拷贝到哪个数组
        //     * @param      dest     the destination array.
        //     destPos: 把源数组的数据拷贝到 目标数组的哪个索引
        //     * @param      destPos  starting position in the destination data.
        //     length: 从源数组拷贝多少个数据到目标数组
        //     * @param      length   the number of array elements to be copied.
        System.arraycopy(src, 0, dest, 0, src.length);
        // int[] src={1,2,3};
        System.out.println("dest=" + Arrays.toString(dest));//[1, 2, 3]

        //currentTimeMillens:返回当前时间距离1970-1-1 的毫秒数
        System.out.println(System.currentTimeMillis());
    }
}

BigInteger和BigDecimal类

image-20211127141003724

常用方法

image-20211127141013005

bigInteger

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

        //当我们编程中,需要处理很大的整数,long 不够用
        //可以使用BigInteger的类来搞定
//        long l = 23788888899999999999999999999l;
//        System.out.println("l=" + l);

        BigInteger bigInteger = new BigInteger("23788888899999999999999999999");
        BigInteger bigInteger2 = new BigInteger("10099999999999999999999999999999999999999999999999999999999999999999999999999999999");
        System.out.println(bigInteger);
        //老韩解读
        //1. 在对 BigInteger 进行加减乘除的时候,需要使用对应的方法,不能直接进行 + - * /
        //2. 可以创建一个 要操作的 BigInteger 然后进行相应操作
        BigInteger add = bigInteger.add(bigInteger2);
        System.out.println(add);//
        BigInteger subtract = bigInteger.subtract(bigInteger2);
        System.out.println(subtract);//减
        BigInteger multiply = bigInteger.multiply(bigInteger2);
        System.out.println(multiply);//乘
        BigInteger divide = bigInteger.divide(bigInteger2);
        System.out.println(divide);//除


    }

BigDecimal

public class BigDecimal_ {
    public static void main(String[] args) {
        //当我们需要保存一个精度很高的数时,double 不够用
        //可以是 BigDecimal
//        double d = 1999.11111111111999999999999977788d;
//        System.out.println(d);
        BigDecimal bigDecimal = new BigDecimal("1999.11");
        BigDecimal bigDecimal2 = new BigDecimal("3");
        System.out.println(bigDecimal);

        //老韩解读
        //1. 如果对 BigDecimal进行运算,比如加减乘除,需要使用对应的方法
        //2. 创建一个需要操作的 BigDecimal 然后调用相应的方法即可
        System.out.println(bigDecimal.add(bigDecimal2));
        System.out.println(bigDecimal.subtract(bigDecimal2));
        System.out.println(bigDecimal.multiply(bigDecimal2));
        //System.out.println(bigDecimal.divide(bigDecimal2));//可能抛出异常ArithmeticException
        //在调用divide 方法时,指定精度即可. BigDecimal.ROUND_CEILING
        //如果有无限循环小数,就会保留 分子 的精度
        System.out.println(bigDecimal.divide(bigDecimal2, BigDecimal.ROUND_CEILING));
    }

日期类

第一代日期类 (Date和SimpleDateFormat)

image-20211127141217387

public class Date01 {
    public static void main(String[] args) throws ParseException {

        //1. 获取当前系统时间
        //2. 这里的Date 类是在java.util包
        //3. 默认输出的日期格式是国外的方式, 因此通常需要对格式进行转换
        //通过指定毫秒数得到时间
        Date d1 = new Date(); 
        System.out.println("当前日期=" + d1);//当前日期=Sat Nov 27 14:12:49 CST 2021

        //通过指定毫秒数得到时间
        Date d2 = new Date(9234567);
        //获取某个时间对应的毫秒数
        System.out.println("d2=" + d2);//d2=Thu Jan 01 10:33:54 CST 1970


        //1. 创建 SimpleDateFormat对象,可以指定相应的格式
        //2. 这里的格式使用的字母是规定好的,不能乱写
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss E");
        String format = sdf.format(d1); // format:将日期转换成指定格式的字符串
        System.out.println("当前日期=" + format); //当前日期=2021年11月27日 02:12:49 星期六

        //1. 可以把一个格式化的String 转成对应的 Date
        //2. 得到Date 仍然在输出时,还是按照国外的形式,如果希望指定格式输出,需要转换
        //3. 在把String -> Date , 使用的 sdf 格式需要和你给的String的格式一样,否则会抛出转换异常
        String s = "1996年01月01日 10:20:30 星期一";
        Date parse = sdf.parse(s);
        System.out.println("parse=" + sdf.format(parse));//parse=1996年01月01日 10:20:30 星期一
    }

第二代日期类(Calendar)

Calendar是一个抽象类,它不能像Date和SimpleDateFormat一样格式化输出。

public class Calendar_ {
    public static void main(String[] args) {
        //1. Calendar是一个抽象类, 并且构造器是private
        //2. 可以通过 getInstance() 来获取实例
        //3. 提供大量的方法和字段提供给程序员
        //4. Calendar没有提供对应的格式化的类,因此需要程序员自己组合来输出(灵活)
        //5. 如果我们需要按照 24小时进制来获取时间, Calendar.HOUR ==改成=> Calendar.HOUR_OF_DAY
        Calendar c = Calendar.getInstance(); //创建日历类对象
        System.out.println("c=" + c);
        //2.获取日历对象的某个日历字段
        System.out.println("年:" + c.get(Calendar.YEAR));
        // 这里为什么要 + 1, 因为Calendar 返回月时候,是按照 0 开始编号
        System.out.println("月:" + (c.get(Calendar.MONTH) + 1));
        System.out.println("日:" + c.get(Calendar.DAY_OF_MONTH));
        System.out.println("小时:" + c.get(Calendar.HOUR));
        System.out.println("分钟:" + c.get(Calendar.MINUTE));
        System.out.println("秒:" + c.get(Calendar.SECOND));
        //Calender 没有专门的格式化方法,所以需要程序员自己来组合显示
        System.out.println(c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH) +
                " " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND) );

    }

第三代日期类(LocalDate、LocalTime、LocalDateTime)

image-20211127142147533

public class LocalDate_ {
    public static void main(String[] args) {
        //第三代日期
        //1. 使用now() 返回表示当前日期时间的 对象
        LocalDateTime ldt = LocalDateTime.now();
        System.out.println(ldt);//2021-11-27T14:22:39.790

        //2. 使用DateTimeFormatter 对象来进行格式化
        // 创建 DateTimeFormatter对象
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = dateTimeFormatter.format(ldt);
        System.out.println("格式化的日期=" + format);//格式化的日期=2021-11-27 14:22:39

        System.out.println("年=" + ldt.getYear());
        System.out.println("月=" + ldt.getMonth());
        System.out.println("月=" + ldt.getMonthValue());
        System.out.println("日=" + ldt.getDayOfMonth());
        System.out.println("时=" + ldt.getHour());
        System.out.println("分=" + ldt.getMinute());
        System.out.println("秒=" + ldt.getSecond());

        LocalDate now = LocalDate.now(); //可以获取年月日
        LocalTime now2 = LocalTime.now();//获取到时分秒
        System.out.println(now);//2021-11-27
        System.out.println(now2);//14:24:29.510

        //提供 plus 和 minus方法可以对当前时间进行加或者减
        //看看890天后,是什么时候 把 年月日-时分秒
        LocalDateTime localDateTime = ldt.plusDays(890);
        System.out.println("890天后=" + dateTimeFormatter.format(localDateTime));//890天后=2024-05-05 14:24:29

        //看看在 3456分钟前是什么时候,把 年月日-时分秒输出
        LocalDateTime localDateTime2 = ldt.minusMinutes(3456);
        System.out.println("3456分钟前 日期=" + dateTimeFormatter.format(localDateTime2));//3456分钟前 日期=2021-11-25 04:48:29
    }
}

Comparator和Comparable(比较器)

Comparable是排序接口,若一个类实现了Comparable接口,则该类支持排序。若该类是Collection接口下的实现类或Map接口的实现类,又或者是数组,则可以使用Collections.sort(对象名)或者Arrays.sort(对象名)来进行排序,因为它们都实现了这个排序接口。

Comparator是自定义比较器,而TreeSet类和TreeMap接口就是典型的使用例子:

public class TreeSet01 {
    public static void main(String[] args) {
        TreeSet treeSet = new TreeSet(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Book b1 = (Book) o1;
                Book b2 = (Book) o2;
                //一般o1 - o2返回正序,o2 - o1返回倒叙
                return b1.getId() - b2.getId();
            }
        });
        treeSet.add(new Book(4));
        treeSet.add(new Book(2));
        treeSet.add(new Book(1));
        System.out.println(treeSet);
    }
}

class Book{
    private int id;

    public Book(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                '}';
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值