Chapter 9: Common Java Classes

Table of contents

9.1: String-related classes: String

        9.1.1: String usage

        9.1.2: String method

        9.1.3: Conversion between String and char[] and byte[]

        9.1.4: Use of StringBuffer and StringBuilder

9.2: Pre-JDK 8 datetime API

9.3: New date and time API in JDK 8

        9.3.1: Use of LocalDate, LocalTime, LocalDateTime

        9.3.2: Instant

9.4: Java Comparator

        9.4.1: Natural sorting java.util.Comparable

        9.4.2: Custom sorting java.util.Comparator

        9.4.3: Comparison of two interfaces:

9.5: System class

9.6: Math class

9.7: BigInteger and BigDecimal


9.1: String-related classes: String

String is a final class that represents an immutable sequence of characters.

        9.1.1: String usage
package com.jiayifeng.java1;

import org.junit.Test;

/**
 * author xiaojia
 * create 2023-09-11 8:09
 *
 * 快捷键:alt + shift + s:构造器
 *
 * 一:String的使用
 */
public class StringTest {
     /*
     1.String实现了Serializable接口:表示字符串是支持序列化的
     2.String实现了Comparable接口:表示String可以比较大小
     3.String内部定义了final char[] value用于存储字符串数据
     4.String:代表不可变的字符序列。简称:不可变性
          体现1:当对字符串重新赋值时,需要重写指定内存区域赋值,不能使用原有的value进行赋值
          体现2:当对现有的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值
          体现3:当调用String的replace()方法修饰指定字符或字符串时,也需要重新指定内存区域
     5.通过字面量的方式(区别于new)给一个字符串赋值,此时的字符串值声明在字符串常量池中
     6.字符串常量池中是不会存储相同内容的字符串的
      */
     @Test
     public void test1(){
          String s1 = "abc";
          String s2 = "abc";
          s1 = "Hello";

         System.out.println(s1 == s2); //比较s1和s2的地址值

         System.out.println(s1);
         System.out.println(s2);
         System.out.println("*********************888");

         String s3 = "abc";
         s3 += "def";

         String s4 = "abc";
         String s5 = s4.replace('a', 'm');
         System.out.println(s4); //abc
         System.out.println(s5); //mbc
     }

     /*
     String的实例化方式:
        方式一:通过字面量定义的方式
        方式二:通过new + 构造器的方式
        面试题:String s = new String("abc");这种方式创建的对象,在内存中创建了几个对象?
            两个:一个是堆空间中的new结构,另一个是char[]对应的常量池中的数据:"char"
      */
    @Test
    public void test2(){
//        通过字面量定义的方式:此时的s1和s2的数据声明在方法区的字符串常量池中
        String s1 = "javaEE";
        String s2 = "javaEE";
//        通过new + 构造器的方式:此时的s3和s4保存的地址值,是数据在堆空间中开辟以后对应的地址值
        String s3 = new String("javaEE");
        String s4 = new String("javaEE");

        System.out.println(s1 == s2);
        System.out.println(s1 == s3);
        System.out.println(s1 == s4);
        System.out.println(s3 == s4); //false
        System.out.println("***************************");

        Person p1 = new Person("Tom",12);
        Person p2 = new Person("Tom",12);
        System.out.println(p1.name.equals(p2.name)); //true
        System.out.println(p1.name == p2.name); //true

        p1.name = "Jerry";
        System.out.println(p2.name); //Tom:不可变性
    }

    /*
    字符串的特性:
        1.常量与常量的拼接结果在常量池。且常量池不会存在相同内容的常量
        2.只要其中有一个是变量,结果就在堆中
        3.如果拼接的结果调用intern()方法,返回值就在常量池中
     */
    @Test
    public void test3(){
        String s1 = "javaEE";
        String s2 = "hadoop";

        String s3 = "javaEEhadoop";
        String s4 = "javaEE" + "hadoop";
        String s5 = s1 + "hadoop";
        String s6 = "javaEE" + s2;
        String s7 = (s1 + s2).intern();

        System.out.println(s3 == s4); //true
        System.out.println(s3 == s5); //false
        System.out.println(s3 == s6); //false
        System.out.println(s5 == s6); //false
        System.out.println(s3 == s7); //true
        System.out.println(s5 == s7); //false
        System.out.println(s6 == s7); //false

        System.out.println(s4 == s7); //true
    }
}
        9.1.2: String method
package com.jiayifeng.java1;

import com.sun.xml.internal.ws.addressing.WsaActionUtil;
import org.junit.Test;

import java.util.Locale;

/**
 * author xiaojia
 * create 2023-09-11 14:36
 */
public class StringMethodTest {
    @Test
    public void test1(){
        String s1 = "HelloWorld";
        System.out.println(s1.length()); //返回字符串的长度:10

        System.out.println(s1.charAt(0)); //返回某索引处的字符:H
        System.out.println(s1.charAt(9)); //d

        System.out.println(s1.isEmpty()); //判断是否是空字符串:false

        String s2 = s1.toLowerCase(); //使用默认语言环境,将String中的所有字符转换为小写
        System.out.println(s1); //HelloWorld:s1是不可变的,仍然为原来的字符串
        System.out.println(s2); //helloworld:改成小写以后的字符串

        String s3 = s1.toUpperCase(); //使用默认语言环境,将String中的所有字符转换为大写
        System.out.println(s1); //HelloWorld
        System.out.println(s3); //HELLOWORLD

        String s4 = "  he  llo world";
        String s5 = s4.trim();
        System.out.println("--------" + s3 + "--------"); //返回字符串的副本,忽略前导空白和尾部空白
        System.out.println("--------" + s4 + "--------");

        System.out.println(s1.equals(s4)); //比较字符串的内容是否相同":false
        System.out.println(s1.equalsIgnoreCase(s4)); //与equals()方法类似,忽略大小写:false

        System.out.println(s1.concat(s4)); //将指定字符串连接到此字符串的结尾

        String s6 = "abc";
        String s7 = "hello";
        System.out.println(s6.compareTo(s7)); //比较两个字符串的大小,涉及到字符串排序:负数-7

        String s8= "北京欢迎你!";
        String s9 = s8.substring(2);
        System.out.println(s8);
        System.out.println(s9); //返回一个新的字符串,它是此字符串从beginIndex开始截取的:欢迎你!

        System.out.println(s8.substring(2,4)); //(左闭右开)返回一个新的字符串,它是此字符串从beginIndex开始截取的,从endIndex(不包含)结束的:欢迎
    }

    @Test
    public void test2(){
        String str1 = "helloworld";
        boolean b1 = str1.endsWith("ld"); //测试此字符是否以指定的后缀结束
        System.out.println(b1); //true

        boolean b2 = str1.startsWith("he"); //测试此字符是否以指定的前缀结束
        System.out.println(b2); //true

        boolean b3 = str1.startsWith("ll",2);
        System.out.println(b3); //true
    }

    @Test
    public void test3(){
//        替换
        String str1 = "北京欢迎你!";
        String str2 = str1.replace('北', '南'); //返回一个新的字符串
        System.out.println(str1); //北京欢迎你
        System.out.println(str2); //南京欢迎你

        String str3 = str1.replace("北京", "上海");
        System.out.println(str3); //上海欢迎你

//        匹配
//        判断str字符串中是否全部由数字组成,即有1-n个数字组成
        String str = "12345";
        boolean matches = str1.matches("\\d+");
        System.out.println(matches); //false

        String tel = "0571-4534289";
//        判断这是否是一个杭州的固定电话
        boolean result = tel.matches("0571-\\d{7,8}");
        System.out.println(result); //true

//        切片
        str = "hello|world|java";
        String[] strs = str.split("\\|");
        for(int i = 0;i < strs.length;i++){
            System.out.println(strs[i]);
        }
    }
}
        9.1.3: Conversion between String and char[] and byte[]
package com.jiayifeng.java2;

import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
 * author xiaojia
 * create 2023-09-12 15:29
 *
 * 一:String与char[]之间的转换:
 *      String --> char[]:调用String的toCharArray()
 *      char[] --> String:调用String的构造器
 *
 * 二:String与byte[]之间的转换:
 *  编码:String --> byte[]:调用String的getBytes()
 *  解码:byte[] --> String:调用String的构造器
 *
 *  编码:字符串 --> 字节(看得懂 ---> 看不懂的二进制数据)
 *  解码:编码的逆过程,字节 -->(看不懂的二进制数据 ---> 看得懂)
 *
 *  说明:解码时,要求使用的字符集必须与编码时使用的字符集一致,否则会出现乱码
 */
public class StringTest {
    @Test
    public void test1(){
        String str1 = "abc123";
        char[] charArray = str1.toCharArray();
        for(int i = 0;i < charArray.length;i++){
            System.out.print(charArray[i] + " ");
        }

        char[] arr = new char[]{'h','e','l','l','o'};
        String str2 = new String(arr);
        System.out.println(str2);
    }

    @Test
    public void test2(){
        String str1 = "abc123中国";
        byte[] bytes = str1.getBytes(); //使用默认的字符集,进行编码
        System.out.println(Arrays.toString(bytes));

        byte[] gbks = new byte[0]; //使用gbk字符集进行编码
        try {
            gbks = str1.getBytes("gbk");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        System.out.println(Arrays.toString(gbks));
        System.out.println("**********");

        String str2 = new String(bytes); //使用默认的字符集,进行解码
        System.out.println(str2);

        String str3 = new String(gbks);
        System.out.println(str3); //出现乱码的原因:编码集和解码集不一致

        String str4 = null;
        try {
            str4 = new String(gbks, "gbk");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        System.out.println(str4); //没有出现乱码原因:编码集和解码集一致
    }
}
        9.1.4: Use of StringBuffer and StringBuilder
package com.jiayifeng.java2;

import org.junit.Test;

/**
 * author xiaojia
 * create 2023-09-14 15:48
 *
 * 一:关于StringBuffer和StringBuilder的使用
 *
 * 二:关于StringBuffer和StringBuilder中的方法使用
 */
public class StringBufferBuilderTest {
    /*
    一:关于StringBuffer和StringBuilder的使用
    1.String和StringBuffer和StringBuilder的异同?
       String:不可变的字符序列;底层使用char[]存储
       StringBuffer:可变的字符序列;线程安全的,效率低;底层使用char[]存储
       StringBuilder:可变的字符序列;jdk5.0新增的,线程不安全的,效率高;底层使用char[]存储

       效率:StringBuilder > StringBuffer > String

       源码分析:
       String str = new String(); //char[] value = new char[0];
       String str1 = new String("abc");char[] value = new char[]{'a','b','c'};

       StringBuffer sb1 = new StringBuffer();//char[] value = new char[16];底层创建了一个长度是16的数组
       sb1.append('a'); //value[0] = 'a';
       sb1.append('b'); //value[1] = 'b';

       StringBuffer sb2 = new StringBuffer("abc"); //char[] value = new char["abc".length() + 16];

       question1: System.out.println(sb2.length()); //3
       question2:扩容问题:如果要添加的数据底层数组盛不下了,那就需要扩容底层的数组
                 默认情况下,扩容为原来的2倍 + 2,同时将原有数组中的元素复制到新的数组中

                 指导意义:在开发过程中,建议大家使用:StringBuffer(int capacity) 或 StringBuilder(int capacity)

     */

    /*
    总结:
        增:append(xxx)
        删:delete(int start,int end)
        改:setCharAt(int n,char ch) / replace(int start,int end,String str)
        查:charAt(int offset,xxx)
        长度:length();
        遍历:for() + charAt() + toString()
     */

    @Test
    public void test() {
        StringBuffer sb1 = new StringBuffer("abc");
        sb1.setCharAt(0,'m');
        System.out.println(sb1); //mbc

        StringBuffer sb2 = new StringBuffer();
        System.out.println(sb2.length()); //0
    }

    @Test
    public void test2(){
        StringBuffer s1 = new StringBuffer("abc");
        s1.append(1);
        s1.append('1'); //提供了很多的append()的方法,用于进行字符串拼接
        System.out.println(s1);

        s1.delete(2,4); //删除指定位置的内容
        System.out.println(s1);

        s1.replace(1,4,"hello"); //把[start,end]位置替换为str
        System.out.println(s1);

        s1.insert(2,false); //在指定位置插入xxx
        System.out.println(s1);

        s1.reverse(); //将当前字符序列逆转
        System.out.println(s1);
    }
}

9.2: Pre-JDK 8 datetime API
package com.jiayifeng.java3;

import com.sun.xml.internal.ws.util.xml.CDATA;
import org.junit.Test;

import java.sql.SQLOutput;
import java.util.Date;

/**
 * author xiaojia
 * create 2023-09-14 17:11
 *
 * 一:JDK 8之前日期和时间的API测试
 */
public class DateTimeTest {
    /*
    java.util.Date类
            |---java.sql.Data类
    1.两个构造器的使用
        >构造器一:Data():创建一个对应当前时间的Data对象
        >构造器二:创建指定毫秒数的的Date对象
    2.两个方法的使用对应的毫秒数(时间戳)

    3.java.sql.Date对应着数据库中的日期类型的变量
        >如何实例化?
        >如何util.Date对象转换为sql.Date对象?
     */
    @Test
    public void test2(){
//        构造器一:Data():创建一个对应当前时间的Data对象
        Date date1 = new Date();
        System.out.println(date1.toString());//Thu Sep 14 17:25:55 CST 2023

        System.out.println(date1.getTime());//1694683555892

//        构造器二:创建指定毫秒数的的Date对象
        Date date2 = new Date(1694683555892l);
        System.out.println(date2.toString());//Thu Sep 14 17:25:55 CST 2023

//        创建java.sql.Date对象
        java.sql.Date date3 = new java.sql.Date(1694683555892L);
        System.out.println(date3);//2023-09-14

//        如何util.Date对象转换为sql.Date对象
//        情况一:
        Date date4 = new java.sql.Date(1694683555892L);
        java.sql.Date date5 = (java.sql.Date)date4;
//        情况二:
        Date date6 = new Date();
        java.sql.Date date7 = new java.sql.Date(date6.getTime());
        System.out.println(date7);//2023-09-14
    }
    @Test
    public void test(){
//        1.System类中的currentTimeMills()
        long time = System.currentTimeMillis();
//        返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差
//        称为事件戳
        System.out.println(time);
    }
}
package com.jiayifeng.java3;

import org.junit.Test;

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

/**
 * author 爱编程的小贾
 * create 2023-09-16 8:23
 *
 * 一:jdk 8之前的日期时间的API测试
 */
public class DateTime1Test {
    /*
    SimpleDateFormat的使用:SimpleDateFormat对日期Date类的格式化和解析
        1.两个操作
            1.1:格式化:日期 ---> 字符串
            1.2:解析:格式化的逆过程,字符串 ---> 日期

        2.SimpleDateFormat的实例化
     */
    @Test
    public void test1() throws ParseException {//异常:对写的日期字符串格式不识别,不是系统默认的格式
//        实例化:使用默认的构造器
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();

//        格式化:日期 ---> 字符串
        Date d1 = new Date();
        System.out.println(d1);//Sat Sep 16 08:35:04 CST 2023

        String format = simpleDateFormat.format(d1);
        System.out.println(format);//23-9-16 上午8:35

//        解析:格式化的逆过程,字符串 ---> 日期
        String str = "23-9-16 上午8:35";
        Date date1 = simpleDateFormat.parse(str);
        System.out.println(date1);//Sat Sep 16 08:35:00 CST 2023

//        ********按照指定的方式格式化和解析:调用带参的构造器*********************
//        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");
//        格式化
        String format1 = sdf1.format(d1);
        System.out.println(format1);//02023.九月.16 公元 08:46 上午
        //2023.09.16 08:48:32
//        解析
        Date d2 = sdf1.parse("2023.09.16 08:48:32");
        System.out.println(d2);//Sat Sep 16 08:48:32 CST 2023
    }

    /*
    calendar日历类(抽象类)的使用:

     */
    @Test
    public void test2(){
//        1.实例化
//        方式一:创建其子类(GregorianCalendar)的对象
//        方式二:调用其静态方法getInstance()
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.getClass());//class java.util.GregorianCalendar

//        2.常用方法
//        get()
        int days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR));

//        set()
        calendar.set(Calendar.DAY_OF_MONTH,22);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);

//        add()
        calendar.add(Calendar.DAY_OF_MONTH,3);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);

//        getTime():日历类 ---> Date
        Date date = calendar.getTime();
        System.out.println(date);//Mon Sep 25 09:18:09 CST 2023

//        setTime():Date ---> 日历类
        Date date1 = new Date();
        calendar.setTime(date1);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);//16
    }
}
9.3: New date and time API in JDK 8
        9.3.1: Use of LocalDate, LocalTime, LocalDateTime
        9.3.2: Instant

                Definition: An instantaneous point on the timeline, which may be used to record a timestamp in the application (the timestamp refers to 00:00:00 on January 1, 1970 GMT (January 1970 Beijing time) The total number of seconds since 08:00:00 on 01st) to now)

                Accuracy: Nanoscale

                1 second = 1000 milliseconds = 10^6 microseconds = 10^9 nanoseconds 

package com.jiayifeng.java3;

import org.junit.Test;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;

/**
 * author 爱编程的小贾
 * create 2023-09-16 9:20
 *
 * 一:jdk 8之中新日期时间API测试
 */
public class DateTimeTest2 {
    /*
    LocalDate、LocalTime、LocalDateTime的使用

     */
    @Test
    public void test1(){
//        now():获取当前的日期、时间、日期+时间
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();

        System.out.println(localDate);
        System.out.println(localTime);
        System.out.println(localDateTime);

//        of():设置指定的年、月、日、时、分、秒。没有偏移量
        LocalDateTime localDateTime1 = LocalDateTime.of(2020,10,6,13,23,33);
        System.out.println(localDateTime1);

//        getXxx():获取相关属性
        System.out.println(localDateTime1.getDayOfMonth());
        System.out.println(localDateTime1.getMonth());

//        体现不可变性
//        withXxx():设置相关属性
        LocalDate localDate1 = localDate.withDayOfMonth(22);
        System.out.println(localDate);//2023-09-16
        System.out.println(localDate1);//2023-09-22

//        体现不可变性
        LocalDateTime localDateTime2 = localDateTime.plusMonths(3);
        System.out.println(localDateTime);//2023-09-16T09:45:52.880
        System.out.println(localDateTime2);//2023-12-16T09:45:52.880

//        减:minus
        }
    /*
    Instant的使用

    */
    @Test
    public void test2(){
//        now():获取本初子午线对应的标准时间
        Instant instant = Instant.now();
        System.out.println(instant);//2023-09-16T02:01:11.290Z(差8小时)

//        添加时间的偏移量
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);//2023-09-16T10:02:13.971+08:00

//        获取自1970年01月01日00时00分00秒(UTC)开始的毫秒数
        long milli = instant.toEpochMilli();
        System.out.println(milli);//1694830048763

//        ofEpochMilli():通过给定的毫秒数获取Instant实例
        Instant instant1 = Instant.ofEpochMilli(1694829971692l);
        System.out.println(instant1);//2023-09-16T02:06:11.692Z
    }

    /*
    DateTimeFormatter:格式化或解析日期、时间
    类似于SimpleDateFormat

     */
    @Test
    public void test(){
//        方式一:预定义的标准格式
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
//        格式化:日期 ---> 字符串
        LocalDateTime localDateTime = LocalDateTime.now();
        String str1 = formatter.format(localDateTime);
        System.out.println(localDateTime);//2023-09-16T10:16:54.890
        System.out.println(str1);//2023-09-16T10:16:54.89

//        解析:字符串 ---> 日期
        TemporalAccessor parse = formatter.parse("2023-09-16T10:16:54.89");
        System.out.println(parse);//{},ISO resolved to 2023-09-16T10:16:54.890

//        方式二:本地化相关的格式
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
//        格式化
        String str2 = formatter1.format(localDateTime);
        System.out.println(str2);//23-9-16 上午10:21


//        方式三:自定义的格式(常用)
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
//        格式化
        String str4 = formatter2.format(LocalDateTime.now());
        System.out.println(str4);//2023-09-16 10:28:04

//        解析
        TemporalAccessor accessor = formatter2.parse("2023-09-16 10:28:04");
        System.out.println(accessor);
    }
}
9.4: Java Comparator
        9.4.1: Natural sorting java.util.Comparable
package com.jiayifeng.java4;

/**
 * author 爱编程的小贾
 * create 2023-09-16 13:26
 */
public class Goods implements Comparable{
    private String name;
    private double price;

    public Goods() {
    }

    public Goods(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

//    指明商品比较大小的方式:按照价格从低到高排序
    @Override
    public int compareTo(Object o) {
        if(o instanceof Goods){
            Goods goods = (Goods)o;
//            方式一:
            if(this.price > goods.price) {
                return 1;
            }else if(this.price < goods.price) {
                return -1;
            }else{
                return 0;
            }
        }
        throw new RuntimeException("传入的数据类型不一致");
    }
}
package com.jiayifeng.java4;

import org.junit.Test;

import java.util.Arrays;

/**
 * author 爱编程的小贾
 * create 2023-09-16 10:44
 *
 * 一:说明:Java中的对象,正常情况下,只能进行等于或不等于的比较。不能使用大于或小于的比较
 *    但在开发场景中,我们需要对多个对象进行排序,言外之意,就需要比较对象的大小。
 *    如何实现?使用两个接口中的任何一个:Comparable或Comparator
 *
 * 二:Comparable接口的使用
 *
 */
public class CompareTest {
    /*
    Comparable接口的使用举例:自然排序
        1.像String、包装类等实现了Comparable接口,重写了compareTo(obj)方法,给出了比较两个对象大小的方式
        2.像String、包装类重写compareTo()方法以后,进行了从小到大的排列
        3.重写compareTo(obj)的规则:
            如果当前对象this大于形参对象obj,则返回正整数
            如果当前对象this小于形参对象obj,则返回负整数
            如果当前对象this等于形参对象obj,则返回零
        4.对于自定义类来说,如果需要排序,我们可以让自定义类实现Comparable接口,重写compareTo(obj)方法
        在compareTo(obj)方法中指明如何排序
     */
    @Test
    public void test1() {
        String[] arr = new String[]{"AA", "CC", "KK", "GG", "JJ", "DD"};

        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));//[AA, CC, DD, GG, JJ, KK]
    }

    @Test
    public void test2() {
        Goods[] arr = new Goods[4];
        arr[0] = new Goods("lenovoMouse",34);
        arr[1] = new Goods("dellMouse",12);
        arr[2] = new Goods("xiaomiMouse",54);
        arr[3] = new Goods("huaweiMouse",65);
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
    }
}

        9.4.2: Custom sorting java.util.Comparator
package com.jiayifeng.java4;

import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

/**
 * author 爱编程的小贾
 * create 2023-09-16 13:52
 *
 * 一:Comparator接口的使用:定制排序
 */
public class CompareTest1 {
    /*
    Comparator接口的使用:
        1.背景:
            当元素的类型没有实现java.lang.Comparable接口而又不方便修改代码,
            或者实现了java.lang.Comparable接口的顺序规则,但又不适合当前的操作,
            那么可以考虑使用Comparator的对象来排序
        2.重写compara(Object o1,Object o2)方法,比较o1,o2的大小
            如果方法返回正整数,则表示o1大于o2;
            如果返回0,表示相等
            返回负整数,表示o1小于o2
     */
    @Test
    public void test(){
        String[] arr = new String[]{"AA", "CC", "KK", "GG", "JJ", "DD"};
        Arrays.sort(arr, new Comparator<String>() {
//            按照字符串从大到小的顺序排列
            @Override
            public int compare(String o1, String o2) {
                if(o1 instanceof String && o2 instanceof String){
                    String s1 = (String)o1;
                    String s2 = (String)o2;
                    return -s1.compareTo(s2);
                }
                throw new RuntimeException("输入的数据类型不一致");
            }
        });
        System.out.println(Arrays.toString(arr));//[KK, JJ, GG, DD, CC, AA]
    }
}
       9.4.3: Comparison of two interfaces:

        Once the method of the Comparable interface is determined, it is guaranteed that the objects of the Comparable interface implementation class can be compared in size at any position.

        The Comparator interface is a temporary comparison.

9.5: System class

        Located in the java.lang package

        Since the constructor of this class is private, an object of this class cannot be created, that is, the class cannot be instantiated. Its internal member variables and member methods are all static, so they can be easily called.

9.6: Math class

        java.lang.Math provides a series of static methods for scientific calculations. The parameter and return value types of its methods are generally double types.

        

Math class
abs absolute value
sqrt square root
pow(double a,double b) a to b power
9.7: BigInteger and BigDecimal

        BigInteger: Represents an immutable arbitrary-precision integer

                Constructor: BigInteger(String val): Constructs a BigInteger object based on a string

        BigDecimal: supports immutable, arbitrary-precision signed decimal fixed-point numbers

                Constructor:

                        public BigDecimal(double val)

                        public BigDecimal(String val)

Guess you like

Origin blog.csdn.net/weixin_63925896/article/details/132798963