day04-面向对象-常用API时间Arrays

news2024/9/26 1:22:27

一、常用API

1.1 StringBuilder类

StringBuilder类
    代表可变的字符串对象,理解为一个操作字符串的容器
    相对于String来说,比本来的操作效率更高
​
StringBuilder常用方法
    public StringBuilder(): 构建一个空的可变字符串对象
    public StringBuilder(String str): 构建一个指定内容的可变字符串对象
​
    public StringBuilder append(任意对象): 拼接数据并返回本身(向后添加)
    public void reverse(): 翻转内容
    public int length(): 返回长度
    public String toString(): 将StringBuilder转为String对象并返回
​
StringBuffer
    跟StringBuilder类功能一样,但是线程安全, 性能较低
public class Demo1 {
    public static void main(String[] args) {
        //1. 创建StringBuilder
        StringBuilder stringBuilder1 = new StringBuilder();
        //2. 字符拼接
        stringBuilder1.append("貂蝉");
        stringBuilder1.append("妲己");
        stringBuilder1.append("张飞");
        stringBuilder1.append("李飞");
        System.out.println(stringBuilder1);//貂蝉妲己张飞李飞
        //3. 反转内容
        stringBuilder1.reverse();
        System.out.println(stringBuilder1);//飞李飞张己妲蝉貂
        //4. 返回长度
        System.out.println(stringBuilder1.length());//8
        //5. 转为字符串
        String string = stringBuilder1.toString();
        System.out.println(string);//飞李飞张己妲蝉貂
    }
​
}

练习

设计一个方法,用于返回任意整型数组的内容,要求返回的数组内容格式如:[11,22,33]
public class Demo2 {
​
    public static void main(String[] args) {
        //定义数组
        int[] arr = {11, 22, 33};
        System.out.println(getArray(arr));
        System.out.println(getArray2(arr));
​
    }
​
    //需求1: 使用String搞
    public static String getArray(int[] arr) {
        //创建一个字符串
        String s = "[";
        //循环遍历
        for (int i = 0; i < arr.length; i++) {
            //获取每个元素,拼接到字符串中
            s += arr[i];
            s = i == arr.length - 1 ? s : s + ",";
        }
        s += "]";
        //返回s
        return s;
    }
    //需求2: 使用StringBuilder搞
    public static String getArray2(int[] arr) {
        //创建一个StringBuilder对象,并设置初始值为"[",
        StringBuilder stringBuilder = new StringBuilder("[");
        //循环遍历
        for (int i = 0; i < arr.length; i++) {
            //获取每个元素,拼接到StringBuilder中
            stringBuilder.append(arr[i]);
            //判断是否是最后一个元素,不是最后一个元素,则拼接","
            if(i != arr.length - 1){
                stringBuilder.append(",");
            }
        }
        //拼接"]"
        stringBuilder.append("]");
        //转换为String
        String string = stringBuilder.toString();
        //返回字符串
        return string;
    }
​
​
}

String和StringBuilder的区别是什么,分别适合什么场景?

答:String:是不可变字符串、频繁操作字符串会产生很多无用的对象,性能差

适合字符串内容不变的场景。

StringBuilder:是内容可变的字符串、拼接字符串性能好、代码优雅

适合字符串内容频繁变化的场景。

1.2 StringBuffer类

    StringBuffer的用法与StringBuilder是一模一样的
    但StringBuilder是线程不安全的  StringBuffer是线程安全的

StringBuilder和StringBuffer的区别是什么,分别适合什么场景?

答:StringBuilder和StringBuffer都是可变字符串

StringBuffer线程安全,性能销差

StringBuilder线程不安全,性能更高

1.3 StringJoiner类

StringJoiner类
    JDK8提供的一个类,和StringBuilder用法类似,但是代码更简洁
​
好处:
    使用它拼接字符串的时候,不仅高效,而且代码的编写更加的方便。
    
场景:
    拼接字符串想指定拼接时的间隔符号,开始符号和结束符号
​
常用方法
    public StringJoiner("间隔符号")  构建一个可变字符串对象,指定拼接时的间隔符号
    public StringJoiner("间隔符号","开始符号","结束符号") 构建一个可变字符串对象,指定拼接时的间隔符号,开始符号和结束符号
​
    public StringJoiner add(String str)   按照格式拼接数据并返回本身
    public int length()  返回长度
    public String toString()  将StringJoiner转为String对象并返回
public class Demo4 {
    public static void main(String[] args) {
        int[] arr = {11, 22, 33};
        System.out.println(getArray(arr));
​
    }
​
    //需求: 设计一个方法,按照格式要求,返回任意类型数组内容:[11,22,33]
    public static String getArray(int[] arr) {
        //创建一个StringJoiner对象,指定间隔符号,开始符号,结束符号
        StringJoiner stringJoiner = new StringJoiner(",", "[", "]");
        //遍历数组,拼接数据
        for (int i = 0; i < arr.length; i++) {
            //拼接数据(add参数为String类型)
            stringJoiner.add(arr[i] + "");
        }
        //返回字符串
        return stringJoiner.toString();
    }
}

1.4 Math类

Math类
    一个专门用于数学运算的工具类
Math类常用方法
    int abs(int a) 返回参数的绝对值
    double ceil(double a) 向上取整(不是四舍五入)
    double floor(double a) 向下取整(不是四舍五入)
    long round(double a) 四舍五入
    int max(int a,int b) 返回两个参数中的较大值
    int min(int a,int b) 返回两个参数中的较小值
    double pow(double a,double b) 返回a的b次幂
    double random() 返回[0.0,1.0)之间的随机正数(0-1不包含1的小数)
public class Demo1 {
    public static void main(String[] args) {
        // int abs(int a) 返回参数的绝对值
        System.out.println(Math.abs(-10));// 10
        // double ceil(double a) 向上取整(不是四舍五入)
        System.out.println(Math.ceil(10.1));// 11.0
        // double floor(double a) 向下取整(不是四舍五入)
        System.out.println(Math.floor(10.9));// 10.0
        // long round(double a) 四舍五入
        System.out.println(Math.round(10.5));// 11
        // int max(int a,int b) 返回两个参数中的较大值
        System.out.println(Math.max(10,20));// 20
        // int min(int a,int b) 返回两个参数中的较小值
        System.out.println(Math.min(10,20));// 10
        // double pow(double a,double b) 返回a的b次幂
        System.out.println(Math.pow(10,3));// 1000.0
        // double random() 返回[0.0,1.0)之间的随机正数(0-1不包含1的小数)
        System.out.println(Math.random());
        //生成[0-10)之间的整数
        System.out.println((int)(Math.random()*10));
    }
}

1.5 System类

System
    代表程序所在系统的一个工具类
​
System类常用方法
    void exit(int status) 终止虚拟机,非0参数表示异常停止
    long currentTimeMillis() 返回当前系统时间的毫秒值 (从1970年1月1日  00:00:00走到此刻的总的毫秒数(1s = 1000ms)。(一般用于计算程序的执行时间(执行后-执行前))

1.6 BigDecimal

BigDecimal
    用于解决浮点型运算时,出现结果失真的问题
​
BigDecimal常用方法
    BigDecimal(double val)     将double转换为BigDecimal (注意:不推荐使用这个,无法总精确运算)
    BigDecimal(String val)     把String转成BigDecimal
    static BigDecimal valueOf(数值型数据)
​
    BigDecimal add(另一BigDecimal对象)  加法
    BigDecimal subtract(另一个BigDecimal对象)  减法
    BigDecimal multiply(另一BigDecimal对象)   乘法
    BigDecimal divide(另一BigDecimal对象)   除法(除不尽报错)
    double doubleValue()   将BigDecimal转换为double
​
    BigDecimal divide (另一个BigDecimal对象,精确几位,舍入模式)  除法、可以控制精确到小数几位
        舍入模式
           RoundingMode.UP         进一
           RoundingMode.FLOOR      去尾
           RoundingMode.HALF_UP    四舍五入
public class Demo3 {
    public static void main(String[] args) {
        //0. 浮点型运算时, 直接+ - * / 可能会出现运算结果失真
        System.out.println(0.1 + 0.2);
        System.out.println(1.0 - 0.32);
        System.out.println(1.015 * 100);
        System.out.println(1.301 / 100);
        System.out.println("=============================");
​
​
        //创建一个BigDecimal对象
            //构造方法
        BigDecimal bigDecimal1 = new BigDecimal("10");
            //静态方法
        BigDecimal bigDecimal2 = BigDecimal.valueOf(3);
        //加减乘除
        BigDecimal add = bigDecimal1.add(bigDecimal2);
        System.out.println(add);//13
​
        BigDecimal subtract = bigDecimal1.subtract(bigDecimal2);
        System.out.println(subtract);//7
​
        BigDecimal multiply = bigDecimal1.multiply(bigDecimal2);
        System.out.println(multiply);//30
        //除法:默认情况只支持整除,否则会抛出异常
//        BigDecimal divide = bigDecimal1.divide(bigDecimal2);
//        System.out.println(divide);//除不尽会报错
        BigDecimal divide = bigDecimal1.divide(bigDecimal2, 2, RoundingMode.HALF_UP);//2位小数,四舍五入
        System.out.println(divide);//3.33
        System.out.println("=============================");
        //将BigDecimal对象转换为double类型
        double value = divide.doubleValue();
        System.out.println(value);
    }
}

二、JDK8之前传统的日期、时间

2.1 Date

Date
    代表的是日期和时间,目前使用java.util包下的Date
​
Date常用方法
    Date()  封装当前系统的时间日期对象(当前)
    Date(long time)  封装指定毫秒值的时间日期对象(指定)
​
    long getTime()  返回从时间原点到此刻经过的毫秒值
    void setTime(long time)  设置时间日期对象的毫秒值
public class Demo1 {
    public static void main(String[] args) {
         //创建一个当前时间的Date对象
        Date date = new Date();
        System.out.println("当前时间为:"+date);//当前时间
​
        //获取当前时间日期对象的毫秒值
        long time = date.getTime();
        System.out.println(time);
​
        //创建一个Date对象,设置时间是当前时间的1小时之前
        Date date1 = new Date(time - 60 * 60 * 1000);
        System.out.println("1小时之前时间为:"+ date1);//当前时间1小时之前
​
        //重新设置时间日期对象的毫秒值
        date1.setTime(time + 60 * 60 * 1000);
        System.out.println("1小时之后1时间为:"+ date1);//当前时间1小时之后
    }
}

 

2.2 SimpleDateFormat

SimpleDateFormat类
    日期时间格式化类,可以对Date对象进行格式化和解析操作
​
SimpleDateFormat常用方法
    public SimpleDateFormat() 空参构造,代表默认格式   2023/9/30 上午2:38
    public SimpleDateFormat("指定格式") 带参构造,指定日期时间格式
​
    public final String format(Date date/long time) 将date日期对象转换为指定格式的字符
    public Date parse(String source) 将字符串转换为date日期对象
    
步骤:
    1.将date日期对象转换为指定格式的字符串
        先new SimpleDateFormat,然后调用format(date)方法
    2.将字符串转换为date日期对象
        先new SimpleDateFormat,然后调用parse("字符串str")方法(字符串str格式和SimpleDateFormat对象的格式必须一致)
​
格式代表符号
      y    年
      M    月
      d    日
      H    时
      m    分
      s    秒
      EEE  星期几
      a    上午/下午

 

public class Demo2 {
    public static void main(String[] args) throws ParseException {
        //1.将date日期对象转换为指定格式的字符串
        Date date = new Date();
        //1.1 创建一个SimpleDateFormat对象,指定日期时间格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //1.2 调用SimpleDateFormat对象的format方法,将date日期对象转换为指定格式的字符串
        String format = simpleDateFormat.format(date);
        System.out.println(format);
​
        System.out.println("------------------------------------------------");
​
        //2.将字符串转换为date日期对象
        //2.1 创建一个SimpleDateFormat对象,指定日期时间格式
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        //2.2 调用SimpleDateFormat对象的parse方法,将字符串转换为date日期对象
        Date parse = simpleDateFormat1.parse("2024年8月30日 11:58:45");//字符串格式和SimpleDateFormat对象的格式必须一致
        System.out.println(parse);
​
​
    }
}
​

2.3 Calendar

Calender类
    代表的是系统此刻时间对应的日历,通过它可以单独获取、修改时间中的年、月、日、时、分、秒等。
​
常见方法
    static Calendar getInstance()  获取当前日历对象
​
    int get(int field) 获职日历中指定信息
    final Date getTime() 获取日期对象
    Long getTimeInMillis() 获取时间毫秒值
​
    void set(int field,int value) 修改个信息
    void add(int field,int amount) 为某个信息增加/减少指定的值
public class Demo3 {
    public static void main(String[] args) {
        //1. 创建日历对象   static Calendar getInstance()
        Calendar calendar = Calendar.getInstance();
        
        //2. 获取: 年 月 日  时 分 秒   int get(int field) 获职日历中指定信息
        int year = calendar.get(Calendar.YEAR);//获取年
        System.out.println(year);
        int month = calendar.get(Calendar.MONTH);//获取月
        System.out.println(month+1);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(day);
        
        //3. 获取日期对象 final Date getTime()
        Date date = calendar.getTime();
        System.out.println(date);
        
        //4. 获取时间毫秒值 Long getTimeInMillis()
        long timeInMillis = calendar.getTimeInMillis();
        System.out.println(timeInMillis);
        
        //5. 修改日期中的某个项 void set(int field,int value)
        calendar.set(Calendar.YEAR,2003);
        calendar.set(Calendar.HOUR_OF_DAY,15);
        Date date1 = calendar.getTime();
        System.out.println(date1);
        
        //6. 为某个信息增加/减少指定的值 void add(int field,int amount)
        calendar.add(Calendar.MONTH,-1);//月份减一
        Date date2 = calendar.getTime();
        System.out.println(date2);
    }
}

三、JDK8开始新增的日期、时间

3.1 LocalDate、 LocalTime、LocalDateTime

三个类
    LocalDate:代表本地日期(年、月、日、星期)
    LocalTime:代表本地时间(时、分、秒、纳秒)
    LocalDateTime:代表本地日期、时间(年、月、日、星期、时、分、秒、纳秒)
​
创建方式
    Xxx.now() 获取时间信息
    Xxx.of(2025, 11, 16, 14, 30, 01)  设置时间信息
​
LocalDateTime转换为LocalDate和LocalTime
    public LocalDate toLocalDate() 转换成一个LocalDate对象
    public LocalTime toLocalTime() 转换成一个LocalTime对象
​
以LocalDate为例子演示常用方法
    获取细节: getYear、getMonthValue、getDayOfMonth、getDayOfYear、getDayOfWeek
    直接修改某个信息,返回新日期对象: withYear、withMonth、withDayOfMonth、withDayOfYear
    把某个信息加多少,返回新日期对象: plusYears、plusMonths、plusDays、plusWeeks
    把某个信息减多少,返回新日期对象: minusYears、minusMonths、minusDays,minusWeeks
    判断两个日期对象,是否相等,在前还是在后:equals isBefore isAfter

 

public class Demo1 {
    public static void main(String[] args) {
        //1. 两种方式创建LocalDateTime
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前时间为:" + now);
        LocalDateTime time = LocalDateTime.of(2025, 5, 20, 13, 14);
        System.out.println("指定时间为:" + time);
​
        //2. 使用LocalDateTime获取LocalDate和LocalTime
        LocalDate localDate = now.toLocalDate();
        System.out.println("当前日期:" + localDate);
​
        LocalTime localTime = now.toLocalTime();
        System.out.println("当前时间:" + localTime);
​
        //3. 获取细节: getYear、getMonthValue、getDayOfMonth、getDayOfYear、getDayOfWeek
        int year = now.getYear();
        Month month = now.getMonth();
        int dayOfMonth = now.getDayOfMonth();
        System.out.println("当前日期为: " + year + "年" + month.getValue() + "月" + dayOfMonth + "日");
​
        //4. 直接修改某个信息,返回新日期对象: withYear、withMonth、withDayOfMonth、withDayOfYear
        LocalDateTime localDateTime = now.withYear(2029).withMonth(1).withDayOfMonth(1);
        System.out.println("修改后的日期:" + localDateTime);
​
        //5. 把某个信息加多少,返回新日期对象: plusYears、plusMonths、plusDays、plusWeeks
        LocalDateTime localDateTime1 = now.plusYears(1).plusMonths(1).plusDays(1);
        System.out.println("加1年1月1日后的日期:" + localDateTime1);
​
        //6. 把某个信息减多少,返回新日期对象: minusYears、minusMonths、minusDays,minusWeeks
        LocalDateTime localDateTime2 = now.minusYears(1).minusMonths(1).minusDays(1);
        System.out.println("减1年1月1日前的日期:" + localDateTime2);
​
        //7. 判断两个日期对象,是否相等,在前还是在后:equals isBefore isAfter
        boolean equals = localDateTime1.equals(localDateTime2);
        System.out.println("两个日期是否相等:" + equals);
​
        System.out.println((localDateTime1.isBefore(localDateTime2) ? "在前面的日期是 " + localDateTime1 : "在前面的日期是 " + localDateTime2));
    }
}

 

3.2 ZoneId、ZonedDateTime

时区和带时区的时间
    时区(ZoneId)
        public static Set<String> getAvailableZoneIds()    获取Java中支持的所有时区
        public static ZoneId systemDefault()   获取系统默认时区
        public static ZoneId of(String zoneId) 获取一个指定时区
    带时区的时间(ZonedDateTime)
        public static ZonedDateTime now()  获取当前时区的ZonedDateTime对象
        public static ZonedDateTime now(ZoneId zone)   获取指定时区的ZonedDateTime对象
public class Demo2 {
    public static void main(String[] args) {
        //获取Java中支持的所有时区
        Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
        System.out.println(availableZoneIds);
        System.out.println("------------------------------------------------");
        //获取系统默认时区
        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println(zoneId);
        //获取一个指定时区
        ZoneId zoneId1 = zoneId.of("Asia/Aden");
        System.out.println(zoneId1);
​
        //获取当前时区的ZonedDateTime对象
        ZonedDateTime now = ZonedDateTime.now();
        System.out.println(now);
        System.out.println("------------------------------------------------");
        //获取指定时区的ZonedDateTime对象
        ZonedDateTime now1 = ZonedDateTime.now(zoneId1);
        System.out.println(now1);
    }
}

 

3.3 DateTimeFormatter(对新版时间做格式化)

DateTimeFormatter:定义格式化时间的格式
    public static DateTimeFormatter ofPattern(时间格式)     获取格式化器对象
​
LocalDateTime的方法
    public String format(DateTimeFormatter formatter)   时间转字符串
    public static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter)   字符串转时间
public class Demo3 {
    public static void main(String[] args) {
        
     // 对日期进行格式化处理,获取字符串   LocalDateTime -----> String
        //1.设置一个当前时间的对象 LocalDateTime
        LocalDateTime now = LocalDateTime.now();
        //2.设置一个时间格式化对象 DateTimeFormatter
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        //3.调用LocalDateTime对象的format方法,把时间格式化
        String format = now.format(pattern);
        System.out.println("格式化后的时间:" + format);//格式化后的时间:2024年08月30日 16:15:33
​
        
    // 2.将字符串转成时间  String -----> LocalDateTime
        LocalDateTime parse = LocalDateTime.parse("2024年08月30日 16:15:33", pattern);
        System.out.println("字符串转时间:" + parse);//字符串转时间:2024-08-30T16:15:33
​
    }
}

四、Arrays

4.1 数组工具类

Arrays
    数组工具类
​
Arrays常用方法
    public static String toString(类型[] arr)  返回数组内容的字符串表示形式
    public static int[] copyOfRange(类[]arr,起始索引,结束索引) 拷贝数组,元素为索引的指定范围,左包含右不包含
    public static copyOf(类型[] arr,int newLength)  拷贝数组,指定新数组的长度
    public static void setAll(double[] array, IntToDoubleFunction generator)  将数组中的数据改为新数据,重新存入数
    public static void sort(类型[ arr); 对数组元素进行升序排列(存储自定义对象下节讲)
public class Demo1 {
    public static void main(String[] args) {
        int[] arr = {1,3,2,5,4};
​
        //public static String toString(类型[] arr)  返回数组内容的字符串表示形式
        String string = Arrays.toString(arr);
        System.out.println(string);//[1, 3, 2, 5, 4]
​
        //public static int[] copyOfRange(类[]arr,起始索引,结束索引) 拷贝数组,元素为索引的指定范围,左包含右不包含
        int[] ints = Arrays.copyOfRange(arr, 0, 2);
        System.out.println(Arrays.toString(ints));//[1, 3]
​
        //public static copyOf(类型[] arr,int newLength)  拷贝数组,指定新数组的长度(长度不足补0)
        int[] ints1 = Arrays.copyOf(arr, 3);
        System.out.println(Arrays.toString(ints1));//[1, 3, 2]
        int[] ints2 = Arrays.copyOf(arr, 5);
        System.out.println(Arrays.toString(ints2));//[1, 3, 2, 5, 4]
        int[] ints3 = Arrays.copyOf(arr, 8);
        System.out.println(Arrays.toString(ints3));//[1, 3, 2, 5, 4, 0, 0, 0]
​
        //public static void setAll(double[] array, IntToDoubleFunction generator)  将数组中的数据改为新数据,重新存入数
        //批量对double类型的数组的每个元素进行相同的处理
        double[] arr1 = {1.0,2.0,3.0,4.0,5.0};
        Arrays.setAll(arr1, new IntToDoubleFunction() {
            @Override
            public double applyAsDouble(int value) {
                System.out.println(value);//value为索引
                return arr1[value] * 2;
            }
        });
        System.out.println(Arrays.toString(arr1));//[2.0, 4.0, 6.0, 8.0, 10.0]
​
​
        //public static void sort(类型[ arr); 对数组元素进行升序排列(存储自定义对象下节讲)
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));//[1, 2, 3, 4, 5]
    }
}

4.2 使用Arrays对对象进行排序

使用Arrays对对象进行排序
    方式1: 自然排序(本案例)
        1、对象实现comparabLe接口,指定泛型
        2、重写compareTo方法、指定排序规则
            正序(由小到大):当前对象的属性)参数对应的属性,返回正数(1),否则返回负数(-1)
            倒序(由大到小):当前对象的属性)参数对应的属性,返回正数(-1),否则返回负数(1)
        3、调用Arrays.sort(arr)方法,完成排序
    排序规则
        返回正数,表示当前元素较大
        返回负数,表示当前元素较小
        返回0,表示相同
public class Demo2 {
    public static void main(String[] args) {
        //1. 定义学生数组对象,保存四个学生进行测试
        Student[] students = new Student[4];
        students[0] = new Student("蜘蛛精", 169.5, 23);
        students[1] = new Student("紫霞1", 163.8, 26);
        students[2] = new Student("紫霞2", 164.8, 26);
        students[3] = new Student("至尊宝", 167.5, 24);
        System.out.println(Arrays.toString(students));
        //2. 指定排序的规则(插入排序:成对插入)
       Arrays.sort(students);
        //3. 打印结果
        System.out.println(Arrays.toString(students));
    }
}
​
class Student implements Comparable<Student> {
    private String name;
    private double height;
    private int age;
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
​
    public int getAge() {
        return age;
    }
​
    public void setAge(int age) {
        this.age = age;
    }
​
    public double getHeight() {
        return height;
    }
​
    public void setHeight(double height) {
        this.height = height;
    }
​
    public Student(String name, double height, int age) {
        this.name = name;
        this.height = height;
        this.age = age;
    }
​
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", height=" + height +
                ", age=" + age +
                '}';
    }
​
​
    @Override
    public int compareTo(Student o) {
        //正序(由小到大):当前对象的属性 > 传入参数o对象的属性,返回正数(1),否则返回负数(-1)
        //倒序(由大到小):当前对象的属性 > 传入参数o对象的属性,返回正数(-1),否则返回负数(1)
        return this.height > o.height ? -1 : 1;//倒序
    }
}
使用Arrays对对象进行排序
    方式2: 比较器排序
        1、调用sort排序方法,参数二传递Comparator按口的实现类对象(匿名内部类实现)
        2、重写compare方法
        3、指定排序规则
    排序规则
        返回正数,表示当前元素较大
        返回负数,表示当前元素较小
        返回0,表示相同
public class  Demo3 {
    public static void main(String[] args) {
        //1. 定义学生数组对象,保存四个学生进行测试
        Teacher[] teachers = new Teacher[4];
        teachers[0] = new Teacher("蜘蛛精", 169.5, 23);
        teachers[1] = new Teacher("紫霞1", 163.8, 26);
        teachers[2] = new Teacher("紫霞2", 164.8, 26);
        teachers[3] = new Teacher("至尊宝", 167.5, 24);
​
        //2. 指定排序的规则(两个参数(数组,比较器(指定排序的规则)))
       Arrays.sort(teachers, new Comparator<Teacher>() {
           @Override
           public int compare(Teacher o1, Teacher o2) {
               //正序:o1属性大于o2属性,返回正数,否则返回负数
               //倒序:o1属性小于o2属性,返回正数,否则返回负数
               return o1.getHeight() > o2.getHeight() ? 1 : -1;//正序
           }
       });
        //3. 打印结果
        System.out.println(Arrays.toString(teachers));
    }
}
​
class Teacher{
    private String name;
    private double height;
    private int age;
​
    public Teacher(String name, double height, int age) {
        this.name = name;
        this.height = height;
        this.age = age;
    }
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
​
    public double getHeight() {
        return height;
    }
​
    public void setHeight(double height) {
        this.height = height;
    }
​
    public int getAge() {
        return age;
    }
​
    public void setAge(int age) {
        this.age = age;
    }
​
    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", height=" + height +
                ", age=" + age +
                '}';
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2089607.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

vue3中vite基于vite-plugin-html的多入口打包

先看打包效果 1、安装vite-plugin-html 2、配置多个入口 每个入口都要有模板(index.html、App.vue、main.js复制一份&#xff0c;根据实际需求调整三个文件) 3、配置vite.config.js 4、代码片段 import { createHtmlPlugin } from vite-plugin-htmlconst htmlParams {minif…

关于springboot的Rest请求映射处理的源码分析(一)

我们在开发中很常见的一种方式是通过请求的类型&#xff0c;也就是restful风格来区别我们的请求接口。 通过请求类型的不同(GET POST PUT DELETE) 来区分即便是请求路径相同的请求。 但是他的底层是如何支持的呢&#xff0c;明明我请求路径都是/user。就因为类型不同就能区分到…

网络层 III(划分子网和构造超网)【★★★★★★】

&#xff08;★★&#xff09;代表非常重要的知识点&#xff0c;&#xff08;★&#xff09;代表重要的知识点。 一、网络层转发分组的过程 分组转发都是基于目的主机所在网络的&#xff0c;这是因为互联网上的网络数远小于主机数&#xff0c;这样可以极大地压缩转发表的大小。…

【Python报错】AttributeError`:`‘NoneType‘ object has no attribute ‘XXXX‘`

&#x1f3ac; 鸽芷咕&#xff1a;个人主页 &#x1f525; 个人专栏: 《C干货基地》《粉丝福利》 ⛺️生活的理想&#xff0c;就是为了理想的生活! 引言 在Python编程中&#xff0c;AttributeError是一个常见的错误类型&#xff0c;它表示尝试访问的对象没有该属性。本文将探讨…

深度强化学习算法(六)(附带MATLAB程序)

深度强化学习&#xff08;Deep Reinforcement Learning, DRL&#xff09;结合了深度学习和强化学习的优点&#xff0c;能够处理具有高维状态和动作空间的复杂任务。它的核心思想是利用深度神经网络来逼近强化学习中的策略函数和价值函数&#xff0c;从而提高学习能力和决策效率…

CNN网络的一些基本知识

CNN 网络的layer介绍 在卷积神经网络&#xff08;Convolutional Neural Network&#xff0c;CNN&#xff09;中&#xff0c;往往包含许多种不同的网络层交替组成&#xff0c;主要有卷积层&#xff08;Convolutional Layer&#xff09;、池化层&#xff08;Pooling Layer&#…

《黑神话:悟空》爆火,对程序员的 5 点启示(2)

前言 继续上篇未完章节…… 4. 需求捕捉 需求有真需求和伪需求的区别&#xff0c;捕捉和理解用户的真需求对于产品非常重要。 在《黑神话&#xff1a;悟空》面世以后&#xff0c;很多玩家都不吝称赞&#xff0c;有玩家这么评论&#xff1a; 不吹牛逼&#xff0c;这一段我眼…

C#中通过TabControl控制MDI子窗体显示切换的实现过程

类似excel表格中各个表单sheet的切换效果&#xff0c;使用tabcontrol控件实现类似的功能。效果如下&#xff1a; 过程涉及父窗体MDIParent1、子窗体main、自定义基础功能类MdiChildBase。 基础功能类MdiChildBase继承自Form创建&#xff0c;定义了一个委托SetTabControlDelega…

apisix 本地开发环境部署

apisix 本地开发环境部署 本地开发环境部署可以采用 docker-compose 部署&#xff0c;配置文件如下 apisix 配置文件 apisix:node_listen: 9080 # APISIX 节点监听地址enable_ipv6: falsehttp:port: 9080 # APISIX HTTP 端口#https:# port: 9443 # APISIX HTTPS 端口# ssl…

《机器学习》K-means 聚类 原理、参数解析、案例实现

1. 引言 随着数据的快速增长和复杂性的不断提高,如何从大量数据中提取有用信息已成为数据科学和人工智能领域的核心挑战。聚类作为一种无监督学习方法,通过将数据分为若干组,使得同一组内的样本具有较高的相似性,而不同组之间的样本差异显著。这种方法被广泛应用于数据分析…

探索极速Python:Sanic框架的魔力

文章目录 探索极速Python&#xff1a;Sanic框架的魔力背景&#xff1a;为什么选择Sanic&#xff1f;Sanic是什么&#xff1f;如何安装Sanic&#xff1f;简单的库函数使用方法场景应用示例常见Bug及解决方案总结 探索极速Python&#xff1a;Sanic框架的魔力 背景&#xff1a;为什…

带你了解RS485通讯网关-天拓四方

在当今工业自动化和智能化的浪潮中&#xff0c;高效、可靠的数据通讯是确保系统运行顺畅的关键。RS485通讯网关作为工业通讯网络中的核心设备&#xff0c;承担着数据传输的重要任务。本文将从RS485通讯网关的技术背景、功能特性、应用场景以及选购要点等方面进行深入探讨&#…

【智能算法应用】基于融合改进A星-麻雀搜索算法求解六边形栅格地图路径规划

目录 1.算法原理2.结果展示3.参考文献4.代码获取 1.算法原理 【智能算法】麻雀搜索算法&#xff08;SSA&#xff09;原理及实现 六边形栅格地图 分析一下地图&#xff1a; 六边形栅格地图上移动可以看做6领域运动&#xff0c;偶数列与奇数列移动方式有所差异&#xff0c;将六…

[每周一更]-(第112期):WDL(Workflow Description Language)说明及使用示例

文章目录 什么是WDL&#xff1f;WDL的基本结构示例 WDL 文件示例任务&#xff1a;字符串反转示例工作流&#xff1a;字符串处理 WDL 文件详解任务&#xff08;Task&#xff09;工作流&#xff08;Workflow&#xff09; 运行示例总结报错参考 什么是WDL&#xff1f; WDL&#x…

Java图形用户界面之Applet设计

Applet设计 前言一、Applet的基本工作原理与使用局限Applet的基本工作原理代码示例 Java Applet 的使用局限Java沙箱安全机制原理 Applet的生命周期与运行方式 二、Applet类Applet类的层次结构常用方法生命周期方法显示方法多媒体支持方法其他方法 三、Applet和GUI基于AWT和Swi…

字符操作函数和内存操作函数

1 字符操作函数 1.strlen size_t strlen ( const char * str ); 函数功能&#xff1a;返回以\0结尾的字符串长度&#xff0c;不包含\0。 注&#xff1a;strlen返回值是一个无符号整数size_t。 #include <stdio.h>int main() {const char*str1 "abcdef";const…

Linux基础软件-selinux库文件swap

作者介绍&#xff1a;简历上没有一个精通的运维工程师。希望大家多多关注作者&#xff0c;下面的思维导图也是预计更新的内容和当前进度(不定时更新)。 Linux进阶部分又分了很多小的部分,我们刚讲完了Linux日常运维。讲的那些东西都算是系统自带的&#xff0c;但是Linux作为一个…

LVGL 控件之圆弧(lv_arc)

目录 一、圆弧部件1、部件组成2、lv_art_t3、圆弧部件角度设置4、圆弧部件旋转设置5、圆弧的模式选择6、圆弧部件的变化率设置7、移除旋钮8、事件9、获取/设置信息相关的 API 二、例程 一、圆弧部件 1、部件组成 圆弧&#xff08;lv_arc&#xff09;部件由三个部分组成&#…

学习之SQL语言之DDL

查询 查询所有数据 SHOW DATABASES&#xff1b; 查询当前数据库 SELECT DATABASE(); 创建 CREATE DATABASE IF NOT EXISTS 数据库名&#xff1b; 删除 DROP DATABASE IF EXISTS 数据库名&#xff1b; 使用 USE 数据库名&#xff1b; 查询当前数据库所有表 SHOW TABLES; 查…

优化大型语言模型微调:MoLA层级专家分配策略

人工智能咨询培训老师叶梓 转载标明出处 大模型&#xff08;LLMs&#xff09;的微调过程中&#xff0c;计算资源的需求巨大&#xff0c;这促使研究者们探索参数高效微调&#xff08;PEFT&#xff09;技术。低秩适应&#xff08;LoRA&#xff09;和专家混合模型&#xff08;MoE…