05—常用API进阶

Object

一个类要么默认继承了Object类,要么间接继承了Object类

Object类的方法都是子类可以直接使用的

常用方法:

  • toString()  默认返回当前对象在堆内存中的地址信息:类的全限名@内存地址
  • equals(Object o)  默认是比较当前对象与另一对象的地址是否相同,相同返回true,不同返回false

toString方法的基本使用

package com.spark.study;

/**
 * Student class
 * description:
 *
 * @author Administrator
 * @date 2023/2/26
 */
public class Student {
    private String name;
    private int age;

    public Student(){

    }
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
package com.spark.study;

/**
 * Test class
 * description:
 *
 * @author Administrator
 * @date 2023/2/26
 */
public class Test {
    public static void main(String[] args) {

        Object obj = new Object();
        // 调用Object类型的toString方法 输出对象的内存地址
        System.out.println(obj.toString());

        // 子类可以调用Object的toString方法
        Student student = new Student();
        System.out.println(student);
    }
}

直接输出对象,默认输出的是对象在堆内存中的地址;Object类的toString方法可以被子类重写,从而输出子类的内容信息。

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

equals方法基本用法

package com.spark.study;

/**
 * Test2 class
 * description:
 *
 * @author Administrator
 * @date 2023/2/26
 */
public class Test2 {
    public static void main(String[] args) {
        Student stu1 = new Student("张三",20);
        Student stu2 = new Student("张三",20);
        System.out.println(stu1.equals(stu2));
        System.out.println(stu1 == stu2);
    }
}

equals默认比较的是两个对象的地址是否相同,而直接比较两个对象地址完全可以用 == 替代equals

equals存在的意义在于子类可以重写Object类的equals方法,用于制定自己的比较规则

@Override
public boolean equals(Object o){
    if(o instanceof Student){
        Student student = (Student)o;
        // 比较两个对象的属性值是否相同,如果相同返回true,表示两个对象相同
        return this.name.equals(student.name) && this.age == student.age;
    }else{
        return false;
    }
}

Objects

Objects类与Object类是继承关系,Objects类从JDK1.7推出

官方在进行字符串比较时,没有用对象自己的equals方法,而是选择了Objects的equals方法来比较两个对象

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Student student = (Student) o;
    return age == student.age && Objects.equals(name, student.name);
}

Objects的equals方法比较结果是一样的,但是更安全。

Objects类的equals方法比较两个对象时,底层会先进行非空判断,从而可以避免空指针异常,再进行equals比较。

StringBuilder

StringBuilder是一个可变的字符串类,可以看成是一个对象容器

作用:提高字符串的操作效率,如拼接、修改等。

StringBuilder构造器

  • public StringBuilder()  创建一个空白的可变字符串对象,不包含任何内容
  • public StringBuilder(String str)  创建一个指定字符串内容的可变字符串对象  

StringBuilder常用方法

  • append  添加数据并返回StringBuilder对象本身
  • reverse  将对象的内容反转
  • replace  将对象内容替换
  • length  返回对象内容长度
  • toString  将StringBuilder转换为String 
package com.spark.stringbuilder;

/**
 * StringBuilderDemo class
 * description:
 *
 * @author Administrator
 * @date 2023/2/26
 */
public class StringBuilderDemo {
    public static void main(String[] args) {
        StringBuilder stringBuilder = new StringBuilder();
        // append 追加内容
        stringBuilder.append("Hello");
        stringBuilder.append("World");
        System.out.println(stringBuilder);

        // reverse 反转内容
        // StringBuilder支持链式编程
        stringBuilder.reverse().append(123).append(33.12);
        System.out.println(stringBuilder);

        // replace 内容替换
        stringBuilder.replace(1,3,"hhh");
        System.out.println(stringBuilder);

        // 内容长度
        System.out.println(stringBuilder.length());

        // 转换为String
        System.out.println(stringBuilder.toString());
    }
}

 Math

包含执行基本数字运算的方法,Math类没有提供公开的构造器

Math类的常用方法:

  • abs(int a)  获取参数绝对值
  • ceil(double a)  向上取整
  • floor(double a)  向下取整
  • round(float a)  四舍五入
  • max(int a,int b)  获取两个int值中的较大值
  • pow(double a,double b)  返回a的b次幂
  • random()  返回值为double的随机值,范围[0.0,1.0)
package com.spark.math;

/**
 * Test class
 * description: Math类的常用方法
 *
 * @author Administrator
 * @date 2023/2/27
 */
public class Test {
    public static void main(String[] args) {
        // 绝对值
        System.out.println(Math.abs(10)); // 10
        System.out.println(Math.abs(-10.3)); // 10.3

        // 向上取整
        System.out.println(Math.ceil(4.00001)); // 5.0
        // 向下取整
        System.out.println(Math.floor(4.9999)); // 4.0
        
        // 四舍五入
        System.out.println(Math.round(4.45)); // 4
        System.out.println(Math.round(4.54)); // 5
        
        // 随机数 0.0--1.0
        System.out.println(Math.random()); // [0.0, 1.0)
    }
}

 System

System功能是通用的,直接通过类名调用即可。

System类常用方法:

  • exit(int status)  终止当前执行的Java虚拟机,非零表示异常终止
  • currentTimeMills()  返回当前系统的时间毫秒值
  • arraycopy(源数组,起始索引,目的数组,起始索引,拷贝个数)  数组拷贝

BigDecimal

使用浮点数直接进行加减乘除运算会出现失真现象,而BigDecimal用于解决浮点型运算失真问题

创建对象BigDecimal封装浮点型数据

public static BigDecimal valueOf(double val); // 包装浮点数成为BigDecimal对象

BigDecimal常用API

  • add(BigDecimal b)  加法
  • subtract(BigDecimal b)  减法
  • multiply(BigDecimal b)  乘法
  • divide(BigDecimal b)  除法
  • divide(BigDecimal b, 精确位数, 舍入模式)  除法  

时间与日期 

7.1 Date类

Date类的对象在Java中代表的是当前所在系统的日期时间

Date类的基本用法

// Date类使用java.util.Date
Date date = new Date();
// 获取当前毫秒值
long time = date.getTime();
// 把时间毫秒值转换成Date对象
Date date2 = new Date(time);

7.2 SimpleDateFormat类

可以对Date对象或时间毫秒值格式化,也可以把字符串的时间形式解析成Date对象

SimpleDateFormat类的基本用法

package com.spark.simpledate;

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

/**
 * Test class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/1
 */
public class Test {
    public static void main(String[] args) throws ParseException {
        // 格式化日期对象
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        System.out.println(sdf.format(date)); // 2023-03-01 22:07:44
        System.out.println(sdf2.format(date)); // 2023年03月01日 22:07:44

        // 解析字符串日期格式
        String dateString = "2021年02月25日";
        // 格式化日期格式需要与字符串日期格式相同
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy年MM月dd日");
        Date parse = sdf3.parse(dateString);
    }
}

7.3 Calendar类

Calendar类代表了系统此刻日期对应的日历对象。Calendar是一个抽象类,不能直接创建对象。

Calendar类的基本用法

package com.spark.calender;

import java.util.Calendar;
import java.util.Date;

/**
 * Test class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/1
 */
public class Test {
    public static void main(String[] args) {
        // 获取当前系统的日历对象
        Calendar cal = Calendar.getInstance();
        System.out.println(cal);

        // 获取日历信息 int get(int field) 获取日期中的某个字段
        // 获取年
        System.out.println(cal.get(Calendar.YEAR));
        // 获取月
        System.out.println(cal.get(Calendar.MONTH) + 1);
        // 获取天
        System.out.println(cal.get(Calendar.DATE));

        // 设置日历信息 set(int field,int value) 修改日历的某个字段信息
        // 设置小时
        cal.set(Calendar.HOUR,12);
        System.out.println(cal.get(Calendar.HOUR));

        // 为某个字段增加或减少指定的值
        // 64天后
        cal.add(Calendar.DAY_OF_YEAR,64);
        // 30分钟前
        cal.add(Calendar.MINUTE,-30);

        // 拿到此刻的日期对象
        Date time = cal.getTime();

        // 拿到此刻时间的毫秒值
        long timeInMillis = cal.getTimeInMillis();
    }
}

7.4 JDK8新增日期类

7.4.1 LocalDate、LocalTime、LocalDateTime

LocalDate:不包含具体时间的日期

LocalTime:不包含日期的时间

LocalDateTime包含了时间及日期

它们分别表示日期、时间、日期时间对象,类的实例为不可变对象

三者构建对象和API是通用的:

① now() 静态方法,根据当前时间创建对象

LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();

② of() 静态方法,指定日期、时间创建对象

LocalDate localDate = LocalDate.of(2023,3,4);
LocalTime localTime = LocalTime.of(11,11,11);
LocalDateTime localDateTime = LocalDateTime.of(2023,3,4,11,11,11);

LocalDate日期对象基本使用

package com.spark.jdk8date;

import java.time.LocalDate;

/**
 * LocalDateTest class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/4
 */
public class LocalDateTest {
    public static void main(String[] args) {
        // 获取当前系统日期
        LocalDate date = LocalDate.now();
        System.out.println(date); // 2023-03-04
        // 指定获取系统日期
        LocalDate date2 = LocalDate.of(1998, 3,27);
        System.out.println(date2); // 1998-03-27

        // 获取年
        System.out.println(date.getYear()); // 2023
        // 获取月
        System.out.println(date.getMonth()); // MARCH
        System.out.println(date.getMonth().getValue()); // 3
        // 获取天
        System.out.println(date.getDayOfYear()); // 当前年的第几天 63
        System.out.println(date.getDayOfMonth()); // 当前月的第几天 4
        System.out.println(date.getDayOfWeek()); // 当前周的第几天 SATURDAY
        System.out.println(date.getDayOfWeek().getValue()); // 6
    }
}

LocalTime时间对象基本使用

package com.spark.jdk8date;

import java.time.LocalTime;

/**
 * LocalTimeTest class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/4
 */
public class LocalTimeTest {
    public static void main(String[] args) {
        // 获取当前系统时间
        LocalTime time = LocalTime.now();
        System.out.println(time); // 20:39:01.890
        // 指定时间
        LocalTime time2 = LocalTime.of(8,2,36);
        System.out.println(time2); // 08:02:36

        // 获取小时
        System.out.println(time.getHour()); // 20
        // 获取分
        System.out.println(time.getMinute()); // 41
        // 获取秒
        System.out.println(time.getSecond()); // 55
        // 获取纳秒
        System.out.println(time.getNano()); // 857000000


    }
}

LocalDateTime日期时间对象基本使用

LocalDateTime综合了LocalDate和LocalTime里面的方法

package com.spark.jdk8date;

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

/**
 * LocalDateTimeTest class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/4
 */
public class LocalDateTimeTest {
    public static void main(String[] args) {
        // 获取当前系统日期时间
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime); // 2023-03-04T20:47:35.194
        // 指定系统日期时间
        LocalDateTime localDateTime2 = LocalDateTime.of(2021,5,1,12,12,12);
        System.out.println(localDateTime2); // 2021-05-01T12:12:12

        // 转换为日期对象
        LocalDate localDate = localDateTime.toLocalDate();
        System.out.println(localDate); // 2023-03-04
        // 转换为时间对象
        LocalTime localTime = localDateTime.toLocalTime();
        System.out.println(localTime); // 20:47:35.194

        // 获取年
        System.out.println(localDateTime.getYear()); // 2023
        // 获取月
        System.out.println(localDateTime.getMonthValue()); // 3
        // 获取日
        System.out.println(localDateTime.getDayOfYear()); // 63
        System.out.println(localDateTime.getDayOfMonth()); // 4
        System.out.println(localDateTime.getDayOfWeek()); // SATURDAY
        System.out.println(localDateTime.getDayOfWeek().getValue()); // 6

        // 获取小时
        System.out.println(localTime.getHour()); // 20
        // 获取分
        System.out.println(localTime.getMinute()); // 47
        // 获取秒
        System.out.println(localTime.getSecond()); // 35
        // 获取纳秒
        System.out.println(localTime.getNano()); // 194000000
    }
}

三个日期对象修改相关的API也通用,以LocalDate举例

方法名说明
plusDays,plusWeeks,plusMonths,plusYears向当前日期对象添加指定的天、周、月、年
minusDays,minusWeeks,minusMonths,minusYears从当前日期对象减去指定的天、周、月、年
withDayOfMonth,withDayOfYear,withMonth,WithYear将月份天数、年份天数、月份、年份修改为指定的值并返回新的日期对象
isBefore,isAfter比较两个日期对象
package com.spark.jdk8date;

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

/**
 * LocalDateTimeTest2 class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/4
 */
public class LocalDateTimeTest2 {
    public static void main(String[] args) {
        // 获取当前系统日期时间对象
        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println(dateTime);

        // 获取当前系统日期
        LocalDate localDate = dateTime.toLocalDate();
        System.out.println(localDate);

        // 添加指定的天、周、月、年
        System.out.println(localDate.plusDays(6));
        System.out.println(localDate.plusWeeks(4));
        System.out.println(localDate.plusMonths(2));
        System.out.println(localDate.plusYears(1));

        // 减去指定的天、周、月、年
        System.out.println(localDate.minusDays(10));
        System.out.println(localDate.minusWeeks(2));
        System.out.println(localDate.minusMonths(4));
        System.out.println(localDate.minusYears(3));

        // 支持链式编程
        System.out.println(localDate.minusYears(2).minusMonths(6));

        // 修改天
        System.out.println(localDate.withDayOfYear(40));

        LocalDate localDate2 = LocalDate.of(2021,3,4);

        // 比较日期
        System.out.println(localDate.isBefore(localDate2));
        System.out.println(localDate.isAfter(localDate2));
    }
}

7.4.2 Instant

Instant类由一个静态工厂方法now()返回当前时间戳

时间戳是包含日期和时间的,Instant可以与Date类进行转换 

package com.spark.jdk8date;

import java.time.Instant;
import java.time.ZoneId;
import java.util.Date;

/**
 * InstantTest class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/4
 */
public class InstantTest {
    public static void main(String[] args) {
        // 时间戳对象
        // 获取当前系统时间
        Instant instant = Instant.now();
        System.out.println(instant); // 标准时间

        // 获取中国时区时间
        Instant instant2 = Instant.now();
        System.out.println(instant2.atZone(ZoneId.systemDefault()));

        // 转换为Date对象
        Date date = Date.from(instant);
        System.out.println(date);
        
        // Date日期转为Instant
        Instant ins = date.toInstant();
        System.out.println(ins);
    }
}

7.4.3 DateTimeFormatter

JDK8新增日期与时间格式器,DateTimeFormatter可以正向格式化,也可以反向格式化,同时可以解析时间字符串

package com.spark.jdk8date;

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

/**
 * DateTimeFormatter class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/4
 */
public class DateTimeFormatterTest {
    public static void main(String[] args) {
        // 获取当前系统日期时间
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);
        LocalDate localDate = localDateTime.toLocalDate();

        // 创建时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMdd");
        // 格式化日期时间对象
        String dateTime = formatter.format(localDateTime);
        System.out.println(dateTime);
        // 反向格式化日期对象
        String date = localDate.format(formatter2);
        System.out.println(date);

        // 解析字符串时间
        String str = "2021-02-03 12:24:36";
        String str2 = "20210223";
        LocalDateTime localDateTime2 = LocalDateTime.parse(str, formatter);
        LocalDate localDate2 = LocalDate.parse(str2,formatter2);
        System.out.println(localDateTime2);
        System.out.println(localDate2);
    }
}

7.4.4 Period

在JDK8中,可以使用Period类来计算时间间隔差异

主要是Period类方法getYear(),getMonths(),getDays()来计算,只能精确到年月日

用于LocalDate之间的比较

package com.spark.jdk8date;

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

/**
 * PeroidTest class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/4
 */
public class PeriodTest {
    public static void main(String[] args) {
        // 获取当前系统日期
        LocalDate localDate = LocalDate.now();
        System.out.println(localDate);
        // 指定一个日期
        LocalDate birthday = LocalDate.of(1998,3,27);
        System.out.println(birthday);

        // 获取间隔对象
        Period period = Period.between(birthday, localDate);

        // 获取年
        System.out.println(period.getYears());
        // 获取月
        System.out.println(period.getMonths());
        // 获取日
        System.out.println(period.getDays());
    }
}

7.4.5 Duration

JDK8中可以使用Duration类计算时间间隔差异

提供了使用基于时间的值测量时间量的方法

用于与LocalDateTime之间的比较,也可以用于Instant之间的比较

package com.spark.jdk8date;

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

/**
 * DurationTest class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/4
 */
public class DurationTest {
    public static void main(String[] args) {
        // 获取当前系统日期时间
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);
        // 获取指定的日期时间对象
        LocalDateTime localDateTime2 = LocalDateTime.of(1998,3,27,0,0,0);
        System.out.println(localDateTime2);

        // 获取时间间隔对象
        Duration duration = Duration.between(localDateTime2,localDateTime);

        // 获取相差天数
        System.out.println(duration.toDays());
        // 获取相差小时数
        System.out.println(duration.toHours());
        // 获取相差分钟数
        System.out.println(duration.toMinutes());
        // 获取相差毫秒数
        System.out.println(duration.toMillis());
    }
}

7.4.6 ChronoUnit

JDK8中可以使用ChronoUnit类在单个时间单位内测量一段时间,可以用于比较所有的时间单位

package com.spark.jdk8date;

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

/**
 * ChronoUnit class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/4
 */
public class ChronoUnitTest {
    public static void main(String[] args) {
        // 获取当前日期时间
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);
        // 获取指定日期时间
        LocalDateTime localDateTime2 = LocalDateTime.of(1998,3,27,0,0,0);
        System.out.println(localDateTime2);

        // 使用ChronoUnit类比较两个日期时间对象
        // 相差的年数
        System.out.println(ChronoUnit.YEARS.between(localDateTime2,localDateTime));
        // 相差的月数
        System.out.println(ChronoUnit.MONTHS.between(localDateTime2,localDateTime));
        // 相差的天数
        System.out.println(ChronoUnit.DAYS.between(localDateTime2,localDateTime));
        // 相差的小时数
        System.out.println(ChronoUnit.HOURS.between(localDateTime2,localDateTime));
        // 相差的分钟数
        System.out.println(ChronoUnit.MINUTES.between(localDateTime2,localDateTime));
        // 相差的秒数
        System.out.println(ChronoUnit.SECONDS.between(localDateTime2,localDateTime));
        // 相差的毫秒数
        System.out.println(ChronoUnit.MILLIS.between(localDateTime2,localDateTime));
    }
}

包装类

包装类是为8种基本数据类型提供的对应的引用数据类型

基本数据类型引用数据类型
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

为什么要提供包装类?

  • Java为了实现一切皆对象的思想,为8种基本数据类型提供对应的引用数据类型
  • 有些类不支持使用基本数据类型,例如泛型

自动装箱和自动拆箱

自动装箱:基本数据类型的变量可以直接赋值给包装类型的变量

自动拆箱:包装类型的变量可以直接赋值给基本数据类型的变量

包装类特有的功能

  • 包装类型的变量默认值是null,容错率更高
  • 可以把数据库转换为字符串
    • 包装类型变量名.toString()
    • 包装类名.toString()
  • 可以把字符串类型的数值转换为真实的数据类型

包装类的基本用法

package com.spark.packagestudy;

/**
 * Test class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/5
 */
public class Test {
    public static void main(String[] args) {
        // 自动装箱
        Integer a1 = 123;
        int a2 = 123;
        Integer a3 = a2;
        System.out.println(a1); // 123
        System.out.println(a2); // 123

        // 自动拆箱
        int b1 = a1;
        System.out.println(b1); // 123

        // 将数值转为字符串
        String str1 = a1.toString();
        String str2 = Integer.toString(a3);
        System.out.println(str1); // 123
        System.out.println(str2 + "123"); // 123123

        // 将字符串数值转为真实数据类型
        String s1 = "456";
        Integer value1 = Integer.parseInt(s1);
        Integer value2 = Integer.valueOf(s1);
        System.out.println(value1); // 456
        System.out.println(value2); // 456
    }
}

正则表达式

正则表达式可以用一些规定的字符来制定规则,并用来校验数据格式的合法性

9.1 基本使用

校验一个QQ号是否正确,QQ号的长度在6—11位之间,必须是全数字

package com.spark.reges;

/**
 * Test class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/5
 */
public class Test {
    public static void main(String[] args) {
        String qq1 = "390317076";
        String qq2 = "3903";
        String qq3 = "390317076712";
        String qq4 = null;

        // 传统方式
        System.out.println(checkQQ(qq1));
        System.out.println(checkQQ(qq2));
        System.out.println(checkQQ(qq3));
        System.out.println(checkQQ(qq4));

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

        // 正则表达式
        System.out.println(checkQQ2(qq1));
        System.out.println(checkQQ2(qq2));
        System.out.println(checkQQ2(qq3));
        System.out.println(checkQQ2(qq4));
    }
    // 传统方式校验QQ号
    public static boolean checkQQ(String qq){
        if(qq==null || qq.length()<6 || qq.length()>11){
            return false;
        }
        char[] chars = qq.toCharArray();
        for (char ch : chars) {
            if(ch<'0' || ch>'9'){
                return false;
            }
        }
        return true;
    }

    // 通过正则表达式校验QQ
    public static boolean checkQQ2(String qq){
        return qq!=null && qq.matches("\\d{6,11}");
    }
}

9.2 匹配规则

字符串对象通过matches方法匹配正则表达式

匹配规则:

① 字符类(默认匹配一个字符)

  • [abc] 只能是a,b或c

  • [^abc] 除了a,b,c之外的任意字符

  • [a-zA-Z] a到z A-Z

  • [a-d[m-p]] ([a-dm-p]联合)

  • [a-z&&[def]] d,e或f(交集)

  • [a-z&&[ ^bc]] a到z,除了b和c

  • [a-z&&[ ^m-p]] a到z,除了m到p

②预定义的字符类(默认匹配一个字符)

  • . 任何字符

  • \d 一个数字 [0-9]

  • \D 非数字 [ ^0-9]

  • \s 一个空白字符串

  • \S 非空白字符

  • \w 英文、数字、下划线

  • \W 非英文、数字、下划线

③贪婪的量词(配合匹配多个字符)

  • x? x,一次或根本不

  • x* x,零次或多次

  • x+, 一次或多次

  • x{},x正好n次

  • x{n,} x至少n次

  • x{n,m} x至少n但不超过m次

package com.spark.reges;

/**
 * Test2 class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/5
 */
public class Test2 {
    public static void main(String[] args) {
        String str1 = "abcdefg";
        String str2 = "adacssd13468";

        // a-z 匹配0次或多次
        System.out.println(str1.matches("[a-z]*"));
        // 字符、数字、不包含下划线 匹配至少一次或多次
        System.out.println(str2.matches("[\\w&&[^_]]+"));
        // 字符、数字,数字范围只有13468 匹配至少6次
        System.out.println(str2.matches("[a-zA-Z0-9&&[^2579]]{6,}"));
    }
}

9.3 常见案例

请编写程序模拟用户输入的手机号、邮箱号验证格式是否正确,并给出提示

package com.spark.reges;

/**
 * Test3 class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/5
 */
public class Test3 {
    public static void main(String[] args) {
        String phone1 = "123456789";
        String phone2 = "13782605442";
        System.out.println(checkPhone(phone1));
        System.out.println(checkPhone(phone2));

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

        String email1 = "asdasdwdsad";
        String email2 = "390317072@qq.com";
        String email3 = "zn4578@163";
        System.out.println(checkEmail(email1));
        System.out.println(checkEmail(email2));
        System.out.println(checkEmail(email3));
    }
    // 校验电话
    public static boolean checkPhone(String phone){
        if(phone == null){
            return false;
        }
        return phone.matches("1[3-9]\\d{9}");
    }
    // 校验邮箱
    public static boolean checkEmail(String email){
        if(email == null){
            return false;
        }
        return email.matches("[a-zA-Z0-9]{1,20}@[a-z0-9]{1,5}(\\.[a-zA-Z0-9]{1,5}){1,2}");
    }
}

Arrays

数组操作工具类,专门用于操作数组元素

常用API:

  • toString 对数组元素内容打印输出

  • sort(类型 [] a) 对数组进行默认升序排序

  • sort(类型 [] a,Comparator<?super T>c) 使用比较器进行排序

  • binarySearch(int [] a,int key) 二分搜索数组中的数据,存在返回索引,不存在返回-1

package com.spark.arrays;

import java.util.Arrays;

/**
 * Test class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/6
 */
public class Test {
    public static void main(String[] args) {
        int [] array = {213,12,63,23,70,21,1,74,4};
        // 输出数组元素内容
        System.out.println(Arrays.toString(array));

        // 对数组进行排序(默认升序)
        Arrays.sort(array);
        System.out.println(Arrays.toString(array));

        // 使用二分查找搜索元素,前提条件是数组已经排好序
        int index1 = Arrays.binarySearch(array, 23);
        int index2 = Arrays.binarySearch(array,999);

        System.out.println(index1);
        System.out.println(index2);
    }
}

Comparator比较器

Arrays默认对有值的数组进行升序排序,当需要自定义排序规则时,可以使用Comparator比较器进行排序

package com.spark.arrays;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Test2 class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/6
 */
public class Test2 {
    public static void main(String[] args) {
        Integer [] array = {45,52,12,35,87,1,35,68};
        // Arrays默认排序为升序
        // 使用Comparator进行降序排列,只支持引用数据类型
        Arrays.sort(array, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });
        System.out.println(Arrays.toString(array));

        List<Student> students = new ArrayList<>();
        students.add(new Student("张三",24,175.5));
        students.add(new Student("小白",18,160.2));
        students.add(new Student("李四",22,180.4));
        students.add(new Student("小红",18,170.2));
        // 自定义排序规则,根据年龄进行升序,之后根据身高进行降序
        Comparator<Student> comparator = Comparator.comparing(Student::getAge);
        Comparator<Student> comparator2 = Comparator.comparing(Student::getHeight).reversed();
        students = students.stream().sorted(comparator.thenComparing(comparator2)).collect(Collectors.toList());
        System.out.println(students);
    }
}
class Student{
    private String name;
    private int age;
    private double height;

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

    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;
    }

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

Lambda表达式

Lambda表达式是jdk8开始后的一种新语法形式。

作用:简化匿名内部类的代码写法

(匿名内部类被重写方法的形参列表)->{
    被重写方法的方法体代码。
}
注:->是语法形式,无实际含义

Lambda表达式只能简化函数式接口的匿名内部类的写法形式

函数式接口:首先必须是接口,其次接口中有且只有一个抽象方法

通常会在接口上加@FunctionalInterface注解,标记该接口必须是满足函数式接口

package com.spark.lambda;

/**
 * Test class
 * description: TODO
 *
 * @author Administrator
 * @date 2023/3/6
 */
public class Test {
    public static void main(String[] args) {
        // 传统方式
        go(new Swim() {
            @Override
            public void swim() {
                System.out.println("老师游的很快");
            }
        });

        // lambda表达式简化
        go(()->{
            System.out.println("学生游的很慢");
        });
        go(()-> System.out.println("运动员游的飞快"));
    }
    public static void go(Swim swim){
        System.out.println("比赛开始-----");
        swim.swim();
        System.out.println("比赛结束-----");
    }
}
interface Swim{
    void swim();
}

lambda表达式的简化规则:

  • 参数类型可以省略不写

  • 如果只有一个参数,参数类型可以省略,同时()也可以省略

  • 如果Lambda表达式的方法体代码只有一行,可以省略大括号不写,同时要省略分号

  • 如果Lambda表达式的方法体代码只有一行,可以省略大括号不写,如果是return语句,必须省略return,同时也必须省略分号

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值