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

(1)常用Api
  • StringBuilder、StringBuffer
  1. StringBuilder代表可变字符串对象,相当于是一个容器,它里面装的字符串是可以改变的,就是用来操作字符串的。
  2. StringBuilder比String更适合做字符串的修改操作,效率会更高,代码也会更简洁。

构造器

说明

public StringBuilder()

创建一个空白的可变的字符串对象,不包含任何内容

public StringBuilder(String str)

创建一个指定字符串内容的可变字符串对象

方法名称

说明

public StringBuilder append(任意类型)

添加数据并返回StringBuilder对象本身

public StringBuilder reverse()

将对象的内容反转

public int length()

返回对象内容长度

public String toString()

通过toString()就可以实现把StringBuilder转换为String

  • StringBuilder类: 代表可变的字符串对象,理解为一个操作字符串的容器 相对于String来说, 本来的操作效率更高
  • StringBuilder常用方法:     
  1. public StringBuilder(): 构建一个空的可变字符串对象
  2. public StringBuilder(String str): 构建一个指定内容的可变字符串对象
  3. public StringBuilder append(任意对象): 拼接数据并返回本身
  4. public void reverse(): 翻转内容
  5. public int length(): 返回长度
  6. public String toString(): 将StringBuilder转为String对象并返回
  • StringBuffer: 跟StringBuilder类功能一样,但是线程安全, 性能较低

public class Demo1 {
    public static void main(String[] args) {
        //1. 创建StringBuilder
        //StringBuilder builder = new StringBuilder();
        StringBuffer builder = new StringBuffer();
        //2. 字符拼接
        builder.append("刘备");
        builder.append("关羽");
        builder.append("张飞");
        System.out.println(builder);
        //3. 反转内容
        builder.reverse();
        System.out.println(builder);
        //4. 返回长度
        int length = builder.length();
        System.out.println("字符串长度:" + length);
        //5. 转为字符串
        String string = builder.toString();
        System.out.println(string);
    }

}
public class Demo2 {

    public static void main(String[] args) {
        //定义数组
        int[] arr = {11, 22, 33};
        String str1 = join1(arr);
        System.out.println(str1);
        System.out.println("------------------");
        String str2 = join2(arr);
        System.out.println(str2);
    }

    //需求1: 使用String搞
    public static String join1 (int[] arr) {
        //1、创建一个字符串str,默认是“[”
        String str = "[";
        //2、循环遍历arr
        for (int i = 0; i < arr.length; i++) {
            //3、获取每个元素,拼接到字符串str上
            str += arr[i] ;
            if (i < arr.length - 1) {
                str += ",";
            }
        }
        str+= "]";
        //4、返回str
        return str;
    }

    //需求2: 使用StringBuilder搞
    public static String join2 (int[] arr) {
        //1、创建一个StringBuilder对象,并设置初始值为"["
        StringBuilder builder = new StringBuilder("[");
        //2、循环遍历数组arr
        for (int i = 0; i < arr.length; i++) {
            //3、将数组的每个元素,拼接到StringBuilder中
            builder.append(arr[i]);
            //4、拼接“,”
            if (i < arr.length -1) {
                builder.append(",");
            }
        }
        //5、拼接"]"
        builder.append("]");
        //6、返回
        return builder.toString();
    }

}
public class Demo3 {

    public static void main(String[] args) {
        test1();
        test2();
    }

    public static void test1() {
        long start = System.currentTimeMillis(); //执行前的毫秒值
        String s = "";
        for (int i = 1; i <= 100000; i++) {
            s += i;
        }
        long end = System.currentTimeMillis(); //执行后的毫秒值
        System.out.println("String做10万次拼接使用时间: " + (end - start) + "毫秒");
    }

    public static void test2() {
        long start = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 100000; i++) {
            sb.append(i);
        }
        long end = System.currentTimeMillis();
        System.out.println("StringBuilder做10万次拼接使用时间: " + (end - start) + "毫秒");
    }
}
  •  StringJoiner类:JDK8提供的一个类,和StringBuilder用法类似,但是代码更简洁
  • 常用方法
  1. public StringJoiner("间隔符号") 构建一个可变字符串对象,指定拼接时的间隔符号
  2. public StringJoiner("间隔符号","开始符号","结束符号") 构建一个可变字符串对象,指定拼接时的间隔符号,开始符号和结束符号
  3. public StringJoiner add(String str) 按照格式拼接数据并返回本身
  4. public int length() 返回长度
  5. public String toString() 将StringJoiner转为String对象并返回

 

构造器

说明

public StringJoiner (间隔符号)

创建一个StringJoiner对象,指定拼接时的间隔符号

public StringJoiner (间隔符号,开始符号,结束符号)

创建一个StringJoiner对象,指定拼接时的间隔符号、开始符号、结束符号

方法名称

说明

public StringJoiner add (添加的内容)

添加数据,并返回对象本身

public int length​()

返回长度 ( 字符出现的个数)

public String toString​()

返回一个字符串(该字符串就是拼接之后的结果)

  •  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)

返回ab次幂的值

public static double random​()

返回值为double的随机值,范围[0.0,1.0)

  • Math类

一个专门用于数学运算的工具类

  • Math类常用方法
  1. int abs(int a) 返回参数的绝对值
  2. double ceil(double a) 向上取整(不是四舍五入)
  3. double floor(double a) 向下取整(不是四舍五入)
  4. long round(double a) 四舍五入
  5. int max(int a,int b) 返回两个参数中的较大值
  6. int min(int a,int b) 返回两个参数中的较小值
  7. double pow(double a,double b) 返回a的b次幂
  8.   double random() 返回[0.0,1.0)之间的随机正数
public class Demo1 {
    public static void main(String[] args) {
        //绝对值
        int abs = Math.abs(-1);
        System.out.println(abs);
        //向上取整(不是四舍五入)
        double ceil = Math.ceil(-3.12);
        System.out.println(ceil);
        //向下取整(不是四舍五入)
        double floor = Math.floor(2.5);
        System.out.println(floor);
        //四舍五入
        long round = Math.round(3.14);
        System.out.println(round);
        //较大值
        int max = Math.max(100, 200);
        System.out.println(max);
        //较小值
        int min = Math.min(100, 200);
        System.out.println(min);
        //a的b次幂
        double pow = Math.pow(2, 3);
        System.out.println(pow);
        //返回[0.0,1.0)之间的随机正数
        double random = Math.random();
        System.out.println(random);
        //生成一个 [0-10)的整数   0.0 ~1.15~ 9.9999
        int i = (int) (Math.random() * 5);
        System.out.println(i);
    }
}
  • System

 

方法名

说明

public static void exit​(int status)

终止当前运行的Java虚拟机。

public static long currentTimeMillis​()

返回当前系统的时间毫秒值形式

  1.  System 代表程序所在系统的一个工具类
  2. System类常用方法
  • void exit(int status) 终止虚拟机,非0参数表示异常停止
  • long currentTimeMillis() 返回当前系统时间的毫秒值
public class Demo2 {
    public static void main(String[] args) {
        //System.exit(1);
        //System.out.println("hello world");
        long millis = System.currentTimeMillis();
        System.out.println(millis);
    }
}
  •  Big Decimal

构造器

说明

public BigDecimal(double val)  注意:不推荐使用这个,无法总精确运算

double转换为BigDecimal

public BigDecimal(String val) 

String转成BigDecimal

方法名

说明

public static BigDecimal valueOf(double val)

转换一个 doubleBigDecimal

public BigDecimal add(BigDecimal b)

加法

public BigDecimal subtract(BigDecimal b)

减法

public BigDecimal multiply(BigDecimal b)

乘法

public BigDecimal divide(BigDecimal b)

除法

public BigDecimal divide (另一个BigDecimal对象,精确几位,舍入模式)

除法、可以控制精确到小数几位

public double doubleValue()

BigDecimal转换为double

  • 用于解决浮点型运算时,出现结果失真的问题
  • BigDecimal常用方法
  1. BigDecimal(double val) 将double转换为BigDecimal (注意:不推荐使用这个) BigDecimal(String val) 把String转成BigDecimal
  2. static BigDecimal valueOf(数值型数据)
  3. BigDecimal add(另一BigDecimal对象) 加法
  4. BigDecimal subtract(另一个BigDecimal对象) 减法
  5. BigDecimal multiply(另一BigDecimal对象) 乘法
  6. BigDecimal divide(另一BigDecimal对象) 除法(除不尽报错)
  7. double doubleValue() 将BigDecimal转换为double
  8. 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("=============================");


        //1、创建BigDecimal对象
        BigDecimal decimal1 = new BigDecimal("10");
        BigDecimal decimal2 = BigDecimal.valueOf(3);
        //2、加减乘除
        //加
        BigDecimal add = decimal1.add(decimal2);
        System.out.println(add);
        //减
        BigDecimal subtract = decimal1.subtract(decimal2);
        System.out.println(subtract);
        //乘
        BigDecimal multiply = decimal1.multiply(decimal2);
        System.out.println(multiply);
        //除: 默认情况支持整除,否则抛出异常
        //BigDecimal divide1 = decimal1.divide(decimal2);
        //System.out.println(divide1);
        BigDecimal divide = decimal1.divide(decimal2, 2, RoundingMode.UP);
        System.out.println(divide);

        //将BigDecimal对象转化成double数据
        double value = divide.doubleValue();
        System.out.println(value);

    }
}
(2)传统日期和时间
  • Date 代表的是日期和时间,目前使用java.util包下的Date
  • Date常用方法
  1. Date() 封装当前系统的时间日期对象
  2. Date(long time) 封装指定毫秒值的时间日期对象
  3. long getTime() 返回从时间原点到此刻经过的毫秒值
  4. 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 - 3600 * 1000);//传入一个毫秒数
        System.out.println(date1);

        //重新设置date对象的毫秒数
        date1.setTime(time + 3600 * 1000);
        System.out.println(date1);
    }
}
  • SimpleDateFormat

 日期时间格式化类,可以对Date对象进行格式化和解析操作

  • SimpleDateFormat常用方法
  1. public SimpleDateFormat() 空参构造,代表默认格式 2023/9/30 上午2:38
  2. public SimpleDateFormat("指定格式") 带参构造,指定日期时间格式
  3. public final String format(Date date/long time) 格式化
  4. public Date parse(String source)

格式代表符号 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 dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //1.2 调用format方法,日期格式化处理
        String format = dateFormat.format(date);
        System.out.println(format);

        System.out.println("----------------------------");
        //2、将字符串,转化成Date日期对象
        //2.1 创建simpleDateFormat对象,指定日期格式(省略)
        //2.2 调用 parse方法将字符串,转化成日期
        Date parse = dateFormat.parse("2024-01-01 12:00:00");
        System.out.println(parse);
    }
}
  • Calender类

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

  • 常见方法
  1. static Calendar getInstance() 获取当前日历对象
  2. int get(int field) 获职日历中指定信息
  3. final Date getTime() 获取日期对象
  4. Long getTimeInMillis() 获取时间毫秒值
  5. void set(int field,int value) 修改个信息
  6. 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);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(year);
        System.out.println(month + 1);
        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)
        //System.out.println(calendar);
        //calendar.set(Calendar.YEAR,2025); //日期域,数据
        //calendar.set(Calendar.HOUR_OF_DAY,10);
        //System.out.println(calendar);
        //Date date1 = calendar.getTime();
        //System.out.println(date1);
        //6. 为某个信息增加/减少指定的值 void add(int field,int amount)
        calendar.add(Calendar.YEAR,1);//日期域,数据
        Date date1 = calendar.getTime();
        System.out.println(date1);
    }
}

构造器

说明

public Date()

创建一个Date对象,代表的是系统当前此刻日期时间。

public Date(long time)

把时间毫秒值转换成Date日期对象。

常见方法

说明

public long getTime()

返回从197011   00:00:00走到此刻的总的毫秒数

public void setTime(long time)

设置日期对象的时间为当前时间毫秒值对应的时间

 

常见构造器

说明

public SimpleDateFormat​(String pattern)

创建简单日期格式化对象,并封装时间的格式

格式化时间的方法

说明

public final String format(Date date)

将日期格式化成日期/时间字符串

public final String format(Object time)

将时间毫秒值式化成日期/时间字符串

 

方法名

说明

public static Calendar getInstance()

获取当前日历对象

public int get(int field)

获取日历中的某个信息。

public final Date getTime()

获取日期对象。

public long getTimeInMillis()

获取时间毫秒值

public void set(int field,int value)

修改日历的某个信息。

public void add(int field,int amount)

为某个信息增加/减少指定的值

(3)新增日期和时间
  • 三个类
  1. LocalDate:代表本地日期(年、月、日、星期)
  2. LocalTime:代表本地时间(时、分、秒、纳秒)
  3. LocalDateTime:代表本地日期、时间(年、月、日、星期、时、分、秒、纳秒)
  • 创建方式
  1. Xxx.now() 获取时间信息
  2. Xxx.of(2025, 11, 16, 14, 30, 01) 设置时间信息
  • LocalDateTime转换为LocalDate和LocalTime
  1. public LocalDate toLocalDate() 转换成一个LocalDate对象
  2. public LocalTime toLocalTime() 转换成一个LocalTime对象
  • 以LocalDate为例子演示常用方法
  1. 获取细节: getYear、getMonthValue、getDayOfMonth、getDayOfYear、getDayOfWeek
  2. 直接修改某个信息,返回新日期对象: withYear、withMonth、withDayOfMonth、withDayOfYear
  3. 把某个信息加多少,返回新日期对象: plusYears、plusMonths、plusDays、plusWeeks
  4. 把某个信息减多少,返回新日期对象: minusYears、minusMonths、minusDays,minusWeeks
  5. 判断两个日期对象,是否相等,在前还是在后: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(2008, 8, 8, 20, 00, 00);
        System.out.println(time);

        //2. 使用LocalDateTime获取LocalDate和LocalTime
        LocalDate localDate = now.toLocalDate(); //获取年月日
        LocalTime localTime = now.toLocalTime();
        System.out.println(localDate);
        System.out.println(localTime);

        //3. 获取细节: getYear、getMonthValue、getDayOfMonth、getDayOfYear、getDayOfWeek
        int year = now.getYear();
        Month month = now.getMonth();
        int day = now.getDayOfMonth();
        System.out.println(year + "--" + month.getValue() +"--" + day);

        //4. 直接修改某个信息,返回新日期对象: withYear、withMonth、withDayOfMonth、withDayOfYear
        LocalDateTime dateTime = now.withMonth(7).withYear(2025);
        System.out.println(now);
        System.out.println(dateTime);

        //5. 把某个信息加多少,返回新日期对象: plusYears、plusMonths、plusDays、plusWeeks
        LocalDateTime dateTime1 = now.plusYears(1).plusMonths(1).plusDays(1);
        System.out.println("dateTime1="+dateTime1);

        //6. 把某个信息减多少,返回新日期对象: minusYears、minusMonths、minusDays,minusWeeks
        LocalDateTime dateTime2 = now.minusYears(1).minusMonths(1);
        System.out.println("dateTime2=" + dateTime2);

        //7. 判断两个日期对象,是否相等,在前还是在后:equals isBefore isAfter
        boolean equals = dateTime1.equals(dateTime2);
        System.out.println(equals);

        boolean before = dateTime1.isBefore(dateTime2); //dateTime1在dateTime2之前
        System.out.println(before);

        boolean after = dateTime1.isAfter(dateTime2); //dateTime1在dateTime2之后
        System.out.println(after);
    }
}
  • 时区和带时区的时间
        时区(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) {
        //时区(ZoneId)
        //获取Java中支持的所有时区
        Set<String> zoneIds = ZoneId.getAvailableZoneIds();
        System.out.println(zoneIds);
        //获取系统默认时区
        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println(zoneId);
        //获取一个指定时区   Asia/Tokyo
        ZoneId zoneId1 = ZoneId.of("Asia/Tokyo");
        System.out.println(zoneId1);

        //带时区的时间
        ZonedDateTime now = ZonedDateTime.now(zoneId1);
        System.out.println(now);
    }
}
  • 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的方法,对时间格式化处理
        String format = now.format(pattern);
        System.out.println(format);
        //将字符串转化成一个日期对象, String ---> LocalDateTime
        LocalDateTime dateTime = LocalDateTime.parse("2008-08-08 20:00:00", pattern);//日期的字符串,日期转化对象
        System.out.println(dateTime);
    }
}

方法名

示例

public static Xxxx now(): 获取系统当前时间对应的该对象

LocaDate ld = LocalDate.now();
LocalTime lt = LocalTime.now();
LocalDateTime ldt = LocalDateTime.now();

public static Xxxx of(…):获取指定时间的对象

LocalDate localDate1 = LocalDate.of(2099 , 11,11);
LocalTime localTime1 = LocalTime.of(9,  8, 59);
LocalDateTime localDateTime1 = LocalDateTime.of(2025, 11, 16, 14, 30, 01);

方法名

说明

public static DateTimeFormatter ofPattern(时间格式)

获取格式化器对象

 

方法名

说明

public String format(DateTimeFormatter formatter)

格式化时间

public static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter)

解析时间

 (4)Arrays
  • 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 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 str = Arrays.toString(arr);
        //System.out.println(str);
        System.out.println(Arrays.toString(arr));
        System.out.println("----------------");

        //public static int[] copyOfRange(类[]arr,起始索引,结束索引) 拷贝数组,元素为索引的指定范围,左包含右不包含
        int[] copyOfRange = Arrays.copyOfRange(arr, 1, 3);
        System.out.println(Arrays.toString(copyOfRange));
        System.out.println("----------------");

        //public static copyOf(类型[] arr,int newLength)  拷贝数组,指定新数组的长度
        int[] copyOf = Arrays.copyOf(arr, 7);
        System.out.println(Arrays.toString(copyOf));
        System.out.println("----------------");

        //public static void setAll(double[] array, IntToDoubleFunction generator)  将数组中的数据改为新数据,重新存入数
        double[] array = {1.0,2.0,3.0,5.0};
        Arrays.setAll(array, new IntToDoubleFunction() {
            @Override
            public double applyAsDouble(int value) {
                return array[value] * 2;
            }
        });
        System.out.println(Arrays.toString(array));
        System.out.println("----------------");

        //public static void sort(类型[ arr); 对数组元素进行升序排列(存储自定义对象下节讲)
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));


    }
}
  • 使用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) {
        //正序(由小到大):当前对象的属性 > 参数对应的属性,返回正数(1),否则返回负数(-1)
        //倒序(由大到小):当前对象的属性 > 参数对应的属性,返回正数(-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;
//            }
//        });
        Arrays.sort(teachers, new Comparator<Teacher>() {
            @Override
            public int compare(Teacher o1, Teacher o2) {
                return o1.getAge() > o2.getAge() ? 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 +
                '}';
    }
}

 

 

 

 

  • 22
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值