常用API-(十)
API(Application Programming Interface):应用程序编程接口,就是已经写好的一些类,程序员可以直接拿去调用即可解决问题的。
Math
帮助我们进行数学计算的工具,里面的方法为静态。
静态类,不用创造对象。
常见方法
abs:获取绝对值
absExact:获取绝对值,超出范围会报错
ceil:向上取整,向着数轴的正方向
floor:向下取整,向着数轴的负方向
round:四舍五入
max:取最大值
min:取最大值
pow:获取a的b次幂
sqrt:开平方根
random:获取[0.0,1.0)之间的随机数
public class Test{
public static void main(String[] args){
//abs
System.out.println(Math.abs(-10));
System.out.println(Math.abs(10));
System.out.println(Math.abs(-10.1));
System.out.println(Math.abs(10.1));
//ceil
System.out.println(Math.ceil(10.1));
System.out.println(Math.ceil(-10.1));
//floor
System.out.println(Math.floor(10.1));
System.out.println(Math.floor(-10.1));
//max
System.out.println(Math.max(10,20));
//min
System.out.println(Math.min(10,20));
//pow
System.out.println(Math.pow(10,2));
//sqrt
System.out.println(Math.sqrt(4));
//random
System.out.println(Math.random());
}
}
/*
10
10
10.1
10.1
11.0
-10.0
10.0
-11.0
20
10
100.0
2.0
0.6820929033064135
*/
范例
判断是否为质数
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
if(isPrime(n)){
System.out.println("质数");
}else{
System.out.println("非质数");
}
}
public static boolean isPrime(int n){
for(int i=2;i<=Math.sqrt(n);i++){
if(n%i==0){
return false;
}
}
return true;
}
}
System
工具类,提供一些与系统相关的方法。
静态,不用创造对象
常见方法
exit
public static void exit(int status)
终止当前运行的Java虚拟机。
方法形参:状态码
- 0:表示当前虚拟机是正常停止
- 非0:表示当前虚拟机异常停止
currentTimeMillis
public static long currentTimeMillis()
返回当前系统的时间的毫秒值形式。
arraycopy
public static void arraycopy(数组源数据,起始索引,目的地数组,起始索引,拷贝个数)
注:
- 若数据源数组和目的地数组都是基本数据类型,两者类型必须一致,否则就会报错
- 在拷贝时需要考虑数组的长度,若超出范围则会报错
- 若数组源数组和目的地操作数都是引用数据类型,子类类型可以赋值给父类类型
例:
package com.ljsblog.domain10;
public class Test{
public static void main(String[] args){
int[] arr1=new int[]{1,2,3,4,5,6,7,8,9,10};
int[] arr2=new int[5];
System.arraycopy(arr1,0,arr2,0,5);
for(int i=0;i<5;i++){
System.out.println(arr2[i]);
}
Student s1=new Student("zhangsan",18);
Student s2=new Student("lisi",19);
Student s3=new Student("wangwu",20);
Student[] sa1=new Student[]{s1,s2,s3};
Person[] sa2=new Person[3];
System.arraycopy(sa1,0,sa2,0,3);
for(int i=0;i<3;i++){
Student s=(Student)sa2[i];
System.out.println(s.getName()+":"+s.getAge());
}
}
}
class Person{
private int age;
private String name;
public Person(){
}
public Person(int age,String name){
this.age=age;
this.name=name;
}
public void setAge(int age) {
this.age=age;
}
public int getAge(){
return age;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}
class Student extends Person{
public Student(){
}
public Student(String name,int age){
super(age,name);
}
}
/*
1
2
3
4
5
zhangsan:18
lisi:19
wangwu:20
*/
Runtime
表示当前虚拟机的运行环境。
非静态,需要创建对象,但不可以new,需要用专门的方法创建
常用方法
Runtime.getRuntime
public static Runtime.getRuntime()
创建对象,无论创建多少个,始终指向一个。
exit
public void exit(int status)
停止虚拟机
- 0:正常关机
- 非0:异常关机
availableProcessors
public int availableProcessors()
获得CPU的线程数
maxMemory
public long maxMemory()
JVM能从系统中获取总内存大小(单位byte)
totalMemory
public long totalMemory()
JVM已经从系统中获取总内存大小(单位byte)
freeMemory
public long freeMemory()
JVM剩余内存大小(单位byte)
exec
public Process exec(String command)
运行cmd命令
范例
import java.io.IOException;
public class Test{
public static void main(String[] args) throws IOException {
Runtime r=Runtime.getRuntime();
System.out.println(r.availableProcessors());
System.out.println(r.maxMemory()/1024/1024);
System.out.println(r.totalMemory()/1024/1024);
System.out.println(r.freeMemory()/1024/1024);
System.out.println(r.exec("notepad"));
r.exit(0);
}
}
Object
所有类都直接或间接继承object类。
构造方法(Object只有空参构造):
public Object()
成员方法
toString
public String toString()
返回对象的字符串表示形式。
默认情况下,Object类中的toString方法返回的是全类名加@加十六进制的哈希值(由对象内存地址和哈希算法算出来的哈希值)。
使用打印语句,打印对象名时,println方法,源码层面会自动调用该对象的toString方法。
若要打印一个对象,想看到属性值的话,可以重写toString方法,在重写的方法中,把对象的属性值进行拼接。
equals
public boolean equals()
比较两个对象是否相等。
若未重写equals方法,默认用Object中的方法进行比较,比较的是地址值是否相等。
大多数情况下地址值对我们意义不大,所以我们会重写,重写后比较的就是对象内部的属性值。
注:String中的equals方法是经过重写的。字符串中的equals方法,先判断参数是否为字符串,若是字符串,在比较内部的属性;若不是字符串,直接返回false。
clone
protected Object clone()
对象克隆
把A对象的属性值完全拷贝给B对象,也叫对象拷贝,对象复制。
方法在底层会创建一个对象,并把原对象中的数据拷贝过去。
细节:
- 重写Object中的clone方法
- 让javabean类实现Cloneable接口
- 创建原对象并调用clone
例:
//学生类
import java.util.StringJoiner;
public class Student implements Cloneable{
private int id;
private String name;
private int[] score=new int[3];
public Student(){}
public Student(int id,String name,int[] score){
this.id=id;
this.name=name;
this.score=score;
}
public void setId(int id){
this.id=id;
}
public int getId(){
return id;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setScore(int[] score){
this.score=score;
}
public int[] getScore(){
return score;
}
@Override
public String toString(){
return "学号:"+id+" 姓名:"+name+" 各科分数:"+arrToString(score);
}
public String arrToString(int[] score){
StringJoiner sj=new StringJoiner(",","{","}");
for(int i=0;i<score.length;i++){
sj.add(""+score[i]);
}
return sj.toString();
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
//测试类
public class Test{
public static void main(String[] args) throws CloneNotSupportedException {
int s[]={88,16,91};
Student stu1=new Student(3,"张三",s);
Student stu2=(Student)stu1.clone();
System.out.println(stu1.toString());
System.out.println(stu2.toString());
}
}
浅克隆和深克隆
浅克隆:对象内部属性无论是基本数据类型还是引用数据类型,都会完全拷贝,其中引用数据类型拷贝的是地址。上边Object常用方法里clone的例子便是浅克隆。
深克隆:基本数据类型拷贝过来,字符串复用,引用数据类型会重新创建新的。
深克隆例:
//学生类
import java.util.StringJoiner;
public class Student implements Cloneable{
private int id;
private String name;
private int[] score=new int[3];
public Student(){}
public Student(int id,String name,int[] score){
this.id=id;
this.name=name;
this.score=score;
}
public void setId(int id){
this.id=id;
}
public int getId(){
return id;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setScore(int[] score){
this.score=score;
}
public int[] getScore(){
return score;
}
@Override
public String toString(){
return "学号:"+id+" 姓名:"+name+" 各科分数:"+arrToString(score);
}
public String arrToString(int[] score){
StringJoiner sj=new StringJoiner(",","{","}");
for(int i=0;i<score.length;i++){
sj.add(""+score[i]);
}
return sj.toString();
}
@Override
protected Object clone() throws CloneNotSupportedException {
int newScore[]=new int[this.score.length];
for(int i=0;i<newScore.length;i++){
newScore[i]=this.score[i];
}
Student stu=(Student)super.clone();
stu.score=newScore;
return stu;
}
}
//测试类
public class Test{
public static void main(String[] args) throws CloneNotSupportedException {
int s[]={88,16,91};
Student stu1=new Student(3,"张三",s);
Student stu2=(Student)stu1.clone();
int u[]=stu1.getScore();
u[1]=2;
System.out.println(stu1.toString());
System.out.println(stu2.toString());
}
}
/*
学号:3 姓名:张三 各科分数:{88,2,91}
学号:3 姓名:张三 各科分数:{88,16,91}
*/
Objects
Objects是一个工具类,提供一些操作对象的方法
常用方法
equals:
public static boolean equals(Object a,Object b)
先做非空判断,再比较两个对象,内部依赖于自己编写的equals。
isNull:
public static boolean isNull(Object obj)
判断对象是否为null,为null返回true,反之。
nonNull:
public static boolean nonNull(Object obj)
判断对象是否为null与isNULL相反。
范例
//学生类
public class Student implements Cloneable{
private int id;
private String name;
public Student(){}
public Student(int id,String name){
this.id=id;
this.name=name;
}
public void setId(int id){
this.id=id;
}
public int getId(){
return id;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}
//测试类
import java.util.Objects;
public class Test{
public static void main(String[] args){
Student s1=new Student(18,"张三");
Student s2=new Student(18,"李四");
Student s3=new Student(18,"李四");
Student s4=null;
System.out.println(Objects.equals(s1,s4));//false
System.out.println(Objects.isNull(s1));//false
System.out.println(Objects.isNull(s4));//true
System.out.println(Objects.nonNull(s1));//true
System.out.println(Objects.nonNull(s4));//false
}
}
BigInteger
整数类型:
- byte,1个字节
- short,2个字节
- int,4个字节
- long,8个字节
若是都不够用的是时候。可以用BigInteger
构造方法和静态方法
- public BigInteger(int num,Random rmd)
- 获取随机大整数,范围0~2的num次方-1
- public BigInteger(String val)
- 获取指定的大整数
- 字符串中必须是整数,否则会报错
- public BigInteger(String val,int radix)
- 获取指定进制的大整数
- 字符串中数字必须是整数,该整数必须要与进制吻合,比如二进制,只能写0和1。
- public static BigInteger valueOf(long val)
- 静态方法获取BigInteger的对象,内部有优化
- 表示范围与long一致
- 在提前把-16~16先创建好BigInteger的对象,若多次获取不会创建新的。
范例:
import java.math.BigInteger;
import java.util.Random;
public class Test{
public static void main(String[] args){
//1.public BigInteger(int num,Random rmd)
Random random=new Random();
BigInteger bd1=new BigInteger(4,random);
System.out.println(bd1);
//2.public BigInteger(String val)
BigInteger bd2=new BigInteger("9999999999999999999999999999999999");
System.out.println(bd2);
//3.public BigInteger(String val,int radix)
BigInteger bd3=new BigInteger("100",2);
System.out.println(bd3);
//4.public static BigInteger valueOf(long val)
BigInteger bd4=BigInteger.valueOf(3);
BigInteger bd5=BigInteger.valueOf(3);
System.out.println(bd4==bd5);
}
}
/*
15
9999999999999999999999999999999999
4
true
*/
注:
- 对象一旦创建里面的数据不能发生改变。
- 只要进行计算都会产生一个新的BigInteger对象
- 若BigInteger表示数字没有超出long的范围,可用静态方法获取
- 若BigInteger表示数字超出long的范围,可用构造方法获取
常见成员方法
add
public BigInteger add(BigInteger val)
加法
subtract
public BigInteger substract(BigInteger val)
减法
multiply
public BigInteger multiply(BigInteger val)
乘法
divide
public BigInteger divide(BigInteger val)
除法,获取商
divideAndRemainder
public BigInteger[] divideAndRemainder(BigInteger val)
除法,获取商和余数
equals
public boolean equals(Object x)
比较是否相同
pow
public BigInteger pow(int exponent)
次幂
max/min
public BigInteger max/min(BigInteger val)
返回最大数或最小数,返回大(小)数的对象,不创建新的对象。
intValue
public int intValue()
转为int类型整数,超出范围数据有误
范例
package com.ljsblog.domain12;
import java.math.BigInteger;
public class Test{
public static void main(String[] args){
BigInteger bd1=BigInteger.valueOf(10);
BigInteger bd2=BigInteger.valueOf(5);
//add
BigInteger bd3=bd1.add(bd2);
System.out.println(bd3);
//subtract
BigInteger bd4=bd1.subtract(bd2);
System.out.println(bd4);
//multiply
BigInteger bd5=bd1.multiply(bd2);
System.out.println(bd5);
//divide
BigInteger bd6=bd1.divide(bd2);
System.out.println(bd6);
//divideAndRemainder
BigInteger[] bd=bd1.divideAndRemainder(bd2);
System.out.println(bd.length);
System.out.println(bd[0]);
System.out.println(bd[1]);
//equals
System.out.println(bd1.equals(bd2));
//pow
BigInteger bd8=bd1.pow(2);
System.out.println(bd8);
//max
BigInteger bd9=bd1.max(bd2);
System.out.println(bd9);
//min
BigInteger bd10=bd1.min(bd2);
System.out.println(bd10);
//intValue
int i=bd2.intValue();
System.out.println(i);
}
}
/*
15
5
50
2
2
2
0
false
100
10
5
5
*/
BigDecima
不可变的,任意精度的有符号十进制数。
用于小数的精确运算,用来表示很大的小数。
构造方法和静态方法
- public BigDecima(double val)
- 有可能不精确,不建议使用
- public BigDecima(String val)
- public static BigDecima valueOf(double val)
范例:
import java.math.BigDecimal;
public class Test{
public static void main(String[] args){
//1.public BigDecima(double val)
BigDecimal bd1=new BigDecimal(0.01);
System.out.println(bd1);
//2.public BigDecima(String val)
BigDecimal bd2=new BigDecimal("0.01");
System.out.println(bd2);
//3.public static BigDecima valueOf(double val)
BigDecimal bd3=BigDecimal.valueOf(10);
BigDecimal bd4=BigDecimal.valueOf(10);
System.out.println(bd3==bd4);
}
}
/*
0.01000000000000000020816681711721685132943093776702880859375
0.01
true
*/
注意:
- 若要表示的数没有超出double范围,建议使用静态方法。
- 若要表示的数超出double范围,建议使用构造方法
- 静态方法中,若我们传递的是0-10之间的整数,那么方法会返回已经创建好的对象,不会重新new
常见成员方法
add
public BigDecimal add(BigDecimal val)
加法
subtract
public BigDecimal subtract(BigDecimal val)
减法
multiply
public BigDecimal multiply(BigDecimal val)
乘法
divide
- public BigDecimal divide(BigDecimal val)
- public BigDecimal divide(BigDecimal val,精确几位,舍入模式)
- 舍入模式用RoundingMode
- 常用四舍五入为RoundingMode.HALF_UP
除法
范例
import java.math.BigDecimal;
public class Test{
public static void main(String[] args){
//add
BigDecimal bd1=BigDecimal.valueOf(10.0);
BigDecimal bd2=BigDecimal.valueOf(2.0);
BigDecimal bd3=bd1.add(bd2);
System.out.println(bd3);
//subtract
BigDecimal bd4=bd1.subtract(bd2);
System.out.println(bd4);
//multiply
BigDecimal bd5=bd1.multiply(bd2);
System.out.println(bd5);
//divide
BigDecimal bd6=bd1.multiply(bd2);
System.out.println(bd6);
BigDecimal bd7=BigDecimal.valueOf(3.0);
BigDecimal bd8=bd1.divide(bd7,2, RoundingMode.HALF_UP);
System.out.println(bd8);
//转换类型,比如转换成double
double d= bd8.doubleValue();
System.out.println(d);
}
}
/*
12.0
8.0
20.00
20.00
3.33
3.33
*/
正则表达式
用来描述或匹配一系列符合某个语句规则的字符串。
作用:
- 校验字符串是否满足规则
- 在一段文本中查找满足要求的内容
注:这些规则无需去背,用的时候可以在api文档中搜索Pattern去查
字符类(只匹配一个字符)
[abc] 只能是a,b,c
[^abc] 除了abc之外的任何字符
[a-zA-Z] a到z,A到Z,包括(范围)
[a-d[m-p]] a到p,或m到p
[a-z&&[def]] a-z和def的交集,为d,e,f
[a-z&&[^bc]] a-z和非bc的交集,(等于[ad-z])
[a-z&&[^m-p]] a到z和除了m到p的交集。(等同于[a-lq-z])
范例:
public class Test{
public static void main(String[] args){
System.out.println("只能是abc");
System.out.println("a".matches("[abc]"));//true
System.out.println("z".matches("[abc]"));//false
System.out.println("ab".matches("[abc]"));//false
System.out.println("ab".matches("[abc][abc]"));//true
System.out.println("不能出现abc");
System.out.println("a".matches("[^abc]"));//false
System.out.println("z".matches("[^abc]"));//true
System.out.println("zz".matches("[^abc]"));//false
System.out.println("zz".matches("[^abc][^abc]"));//true
System.out.println("a到z,A到Z(包括头尾的范围)");
System.out.println("a".matches("[a-zA-Z]"));//true
System.out.println("z".matches("[a-zA-Z]"));//true
System.out.println("aa".matches("[a-zA-Z]"));//false
System.out.println("zz".matches("[a-zA-Z]"));//false
System.out.println("0".matches("[a-zA-Z]"));//false
System.out.println("a到d,或m到p");
System.out.println("a".matches("[a-d[m-p]]"));//true
System.out.println("d".matches("[a-d[m-p]]"));//true
System.out.println("m".matches("[a-d[m-p]]"));//true
System.out.println("p".matches("[a-d[m-p]]"));//true
System.out.println("e".matches("[a-d[m-p]]"));//false
System.out.println("0".matches("[a-d[m-p]]"));//false
System.out.println("a-z和def的交集,为def");
System.out.println("a".matches("[a-z&&[def]]"));//false
System.out.println("d".matches("[a-z&&[def]]"));//true
System.out.println("0".matches("[a-z&&[def]]"));//false
System.out.println("a-z和非bc的交集,等同于[ad-z]");
System.out.println("a".matches("[a-z&&[^bc]]"));//true
System.out.println("b".matches("[a-z&&[^bc]]"));//false
System.out.println("0".matches("[a-z&&[^bc]]"));//false
System.out.println("a到z和除了m和p的交集,等同于[a-lq-z]");
System.out.println("a".matches("[a-z&&[^m-p]]"));//true
System.out.println("m".matches("[a-z&&[^m-p]]"));//false
System.out.println("0".matches("[a-z&&[^m-p]]"));//false
}
}
预定义字符(只匹配一个字符)
. 任何字符
\d 一个数字[0-9]
\D 非数字[^0-9]
\s 一个空白字符[\t\n\x0B\f\r]
\S 非空白字符[^\s]
\w [a-zA-Z_0-9]英文,数字,下划线
\W [^\w]一个非单词字符
范例:
public class Test{
public static void main(String[] args){
System.out.println(".只能表示一个字符");
System.out.println("你".matches("."));//true
System.out.println("你".matches(".."));//false
System.out.println("你们".matches(".."));//true
System.out.println("\\\\d只能是任意的一位数字");
System.out.println("简单来记:两个\\表示一个\\");
System.out.println("a".matches("\\d"));//false
System.out.println("3".matches("\\d"));//true
System.out.println("333".matches("\\d"));//false
System.out.println("\\\\w只能是一位单词字符[a-zA-Z_0-9]");
System.out.println("z".matches("\\w"));//true
System.out.println("2".matches("\\w"));//true
System.out.println("21".matches("\\w"));//false
System.out.println("你".matches("\\w"));//false
System.out.println("非单词字符");
System.out.println("你".matches("\\W"));//true
}
}
数量词
X? X,一次或0次
X* X,零次或多次
X+ X,一次或多次
X{n} X,正好n次
X{n,} X,至少n次
X{n,m} X,至少n但不超过m次
范例
public class Test{
public static void main(String[] args){
System.out.println("必须是数字,字母和下划线,至少6位");
System.out.println("sdasfd4544".matches("\\w{6,}"));//true
System.out.println("s44".matches("\\w{6,}"));//false
System.out.println("必须是数字和字符,必须是4位");
System.out.println("12dF".matches("[a-zA-Z0-9]{4}"));//true
System.out.println("12_F".matches("[a-zA-Z0-9]{4}"));//false
System.out.println("12dF".matches("[\\w&&[^_]]{4}"));//true
System.out.println("12_F".matches("[\\w&&[^_]]{4}"));//false
}
}
分组
分组就是一个小括号。
正则表达式中分组有两种:捕获分组和非捕获分组。
捕获分组
每组都是由组号(序号)的,组号从1开始,连续不间断,以左括号为基准(注:不是以整个括号为基准),最左边的是第一组,其次第二组,以此类推。
正则内部使用:
\\组号
正则外部使用:
$组号
例:
(\\d+)(\\d+)(\\d+)
第一个(\\d+)是第一组,第二个(\\d+)是第二组,第三个(\\d+)是第三组。
(\\d+(\\d+))(\\d+)
(\\d+(\\d+))第一组,第一组里面的(\\d+)是第二组,外面的(\\d+)是第三组
public class Test1 {
public static void main(String[] args) {
//判断一个字符串的开始字符和结束字符是否一致,只考虑单个字符
String s1="a123a";
String s2="b456b";
String s3="17891";
String s4="&abcd";
System.out.println(s1.matches("(.).+\\1"));
System.out.println(s2.matches("(.).+\\1"));
System.out.println(s3.matches("(.).+\\1"));
System.out.println(s4.matches("(.).+\\1"));
System.out.println();
//判断一个字符串的开始字符和结束字符是否一致,可多个字符
String s5="ab123ab";
String s6="b456b";
String s7="123789123";
String s8="a&caabca&b";
System.out.println(s5.matches("(.+).+\\1"));
System.out.println(s6.matches("(.+).+\\1"));
System.out.println(s7.matches("(.+).+\\1"));
System.out.println(s8.matches("(.+).+\\1"));
System.out.println();
//判断一个字符串的开始字符和结束字符是否一致,开始部分内部每个字符也需要一致
String s9="aaa123aaa";
String s10="bbb456bbb";
String s11="111789111";
String s12="aacaabcaac";
System.out.println(s9.matches("((.)\\2*).+\\1"));
System.out.println(s10.matches("((.)\\2*).+\\1"));
System.out.println(s11.matches("((.)\\2*).+\\1"));
System.out.println(s12.matches("((.)\\2*).+\\1"));
System.out.println();
//字符串内容去重
String s="这是一一一个个网网网网站站";
//注:replaceAll可以识别正则表达式,replace不能
String str=s.replaceAll("(.)\\1+","$1" );
System.out.println(str);
}
}
/*
true
true
true
false
true
true
true
false
true
true
true
false
这是一个网站
*/
非捕获分组
分组之后不需要再用本组数据,仅仅是把数据括起来
(?:正则)
获取所有
(?=正则)
获取前面部分
(?!正则)
获取不是指定内容的前面部分
范例一
//请编写正则表达式验证用户名是否满足要求。
//要求:大小写字母,数字,下划线一共4-16位。
public class Test{
public static void main(String[] args){
String regex="\\w{4,16}";
System.out.println("ljs".matches(regex));
}
}
//请编写正则表达式验证身份证号码是否满足要求。
//按照身份证号码格式验证。
public class Test{
public static void main(String[] args){
String regex2="[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[\\dxX]";
System.out.println("13118819991104181x".matches(regex2));
System.out.println("121158199911041819".matches(regex2));
System.out.println("021158199911041819".matches(regex2));
System.out.println("021158199900041819".matches(regex2));
}
}
/*
true
true
false
false
*/
范例二
/*有如下文本,请按照要求爬取数据。Java自从95年问世以来,经历了很多版本,目前企业中用的最多的是lavaB和Java11,因为这两个是长期支持版本,下一个长期支持版本是Java17,相信在未来不久Java17也会逐渐登上历史舞台
要求:找出里面所有的JavaXX
*/
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test{
public static void main(String[] args){
String str="Java自从95年问世以来,经历了很多版本,目前企业中用的最多的是Java8和Java11,因为这两个是长期支持版本,下一个长期支持版本是Java17,相信在未来不久Java17也会逐渐登上历史舞台";
//Pattern:表示正则表达式
Pattern p=Pattern.compile("Java\\d{0,2}");
//Matcher:文本适配器,按照正则表达式的规则读取字符串,从头开始读取
//m要在str中找符合规则的字符串
Matcher m=p.matcher(str);
//用文本适配器从头读取,寻找是否有满足的字符串
//若无,m.find()返回false
//若有,返回true,在底层记录字符串的起始索引和结束索引+1
//第一次[0,4)
while(m.find()){
System.out.println(m.group());
System.out.print("start:"+m.start());//起始索引
System.out.println("\tend:"+m.end());//结束索引+1
}
}
}
/*
Java
start:0 end:4
Java8
start:33 end:38
Java11
start:39 end:45
Java17
start:69 end:75
Java17
start:83 end:89
*/
JDK7时间类
Date
Date类是JDK写好的Javabean类,用来描述时间,精确到毫秒。
- 空参构造:public Date()
- 默认表示系统当前时间。
- 有参构造:public Date(long time)
- 表示指定的时间。
- public void setTime(long time)
- 设置/修改毫秒值
- public long getTime()
- 获取时间对象的毫秒值
包:java.util.Date
注:打印对象名会显示具体时间。
范例:
//任务一:打印时间原点开始一年之后的时间
import java.util.Date;
public class Test{
public static void main(String[] args){
Date date=new Date(1000L*60*60*24*365);
System.out.println(date);
}
}
//Fri Jan 01 08:00:00 CST 1971
//任务二:定义任意两个Date对象,比较一下哪个时间在前,哪个在后
import java.util.Date;
import java.util.Random;
public class Test{
public static void main(String[] args){
Random r=new Random();
Date d1=new Date(Math.abs(r.nextInt()));
Date d2=new Date(Math.abs(r.nextInt()));
System.out.println(d1);
System.out.println(d2);
long t1=d1.getTime();
long t2=d2.getTime();
if(t1>t2){
System.out.println("第一个时间在后,第二个时间在前");
}else if(t1<t2){
System.out.println("第二个时间在后,第一个时间在前");
}else{
System.out.println("两个时间相等");
}
}
}
/*
Tue Jan 13 08:56:18 CST 1970
Fri Jan 23 02:30:33 CST 1970
第二个时间在后,第一个时间在前
*/
SimpleDateFormat
作用:
-
格式化:把时间变成我们喜欢的格式
-
解析:把字符串的时间变成Date对象
-
空参构造:public SimpleDateFormat()
- 默认格式
-
有参构造:Public SimpleDateFormat(String pattern)
- 指定格式
-
public final String format(Date date)
- 格式化:日期对象变成字符串
-
public Date parse(String source)
- 解析:字符串变成日期对象
包:java.text.SimpleDateFormat
范例1:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test{
public static void main(String[] args) throws ParseException {
//1.利用空参构造创建SimpleDateFormat对象,默认格式
SimpleDateFormat sdf1=new SimpleDateFormat();
Date d1=new Date();
String str1=sdf1.format(d1);
System.out.println(str1);
//2.利用有参构造创建SimpleDateFormat对象,默认格式
SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str2=sdf2.format(d1);
System.out.println(str2);
//3.定义一个字符串变成Date
String str3="2023-03-09 17:00:01";
SimpleDateFormat sdf3=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d2=sdf3.parse(str3);
System.out.println(d2.getTime());
}
}
/*
23-3-9 下午5:26
2023-03-09 17:26:20
1678352401000
*/
范例2:
//假如你的出生年月日为:2000-11-11,请用字符串表示这个数据,并将其转换为2000年11月11日
import java.text.ParseException;
import java.util.Date;
import java.text.SimpleDateFormat;
public class Test{
public static void main(String[] args) throws ParseException {
String str1="2000-11-11";
SimpleDateFormat spd1=new SimpleDateFormat("yyyy-MM-dd");
Date d1=spd1.parse(str1);
SimpleDateFormat spd2=new SimpleDateFormat("yyyy年MM月dd日");
String str2=spd2.format(d1);
System.out.println(str2);
}
}
Calender
Calender代表系统当前时间的日历对象,可单独修改,获取时间中的年,月,日
注:
-
Calender是一个抽象类,不能直接创建对象,而是通过静态方法getInstance获取子类对象。
- 底层原理:根据系统的不同时区获取不同的日历对象,默认表示当前时间,会把时间中的纪元,年,月,日,时,分,秒,星期,等等都放到一个数组当众
-
月份:范围0-11,若取出0,实际上是1月
-
星期:在外国人眼里,星期日是一周中的第一天
常用方法
- public static Calender getInstance()
- 获取当前时间的日历对象(子类对象)
- public final Date getTime()
- 获取日期对象
- public final setTime(Date date)
- 给日历设置日期对象
- public long getTimeInMillis()
- 拿到时间毫秒值
- public long setTimeInMillis(long millis)
- 给日历设置时间毫秒值
- public int get(int field)
- 取日期中的某个字段信息
- public void set(int field,int value)
- 修改日历的某个字段信息
- public void add(int field,int amount)
- 为某个字段增加/减少指定的值
范例
import java.util.Calendar;
import java.util.Date;
public class Test{
public static void main(String[] args){
Calendar calendar=Calendar.getInstance();
Date d=new Date(0L);
calendar.setTime(d);
System.out.println(calendar.getTime());
calendar.set(Calendar.YEAR,2000);
calendar.set(Calendar.MONTH,11);
calendar.set(Calendar.DAY_OF_MONTH,10);
System.out.println(calendar.getTime());
calendar.add(Calendar.YEAR,1);
System.out.println(calendar.getTime());
int year=calendar.get(Calendar.YEAR);
//Calendar的月份是0-11,想获取对应的月份,需加1
int month=calendar.get(Calendar.MONTH)+1;
int date=calendar.get(Calendar.DAY_OF_MONTH);
int week=calendar.get(Calendar.DAY_OF_WEEK);
System.out.println(year+","+month+","+date+","+getWeek(week));
}
public static String getWeek(int index){
String[] arr={"","星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
return arr[index];
}
}
/*
Thu Jan 01 08:00:00 CST 1970
Sun Dec 10 08:00:00 CST 2000
Mon Dec 10 08:00:00 CST 2001
2001,12,10,星期一
*/
JDK8时间类
JDK8的时间日期是不可变的,若修改减少增加时间,调用者不会改变,而是返回一个新的时间
Date类
ZoneId
时区
常用方法
-
static Set getAvailableZoneIds()
- 获取java中支持的所有时区
-
static ZoneId systemDefault()
- 获取系统的默认时区
-
static ZoneId of(String zoneId)
- 获取一个指定时区
范例
import java.time.ZoneId;
import java.util.Set;
public class Test{
public static void main(String[] args){
//1.获取所有时区名称
Set<String> zoneIds= ZoneId.getAvailableZoneIds();
//System.out.println(zoneIds);
//2.获取当前系统的默认时区
ZoneId zoneId=ZoneId.systemDefault();
System.out.println(zoneId);
//获取指定时区
ZoneId zoneId1=ZoneId.of("Etc/GMT+8");
System.out.println(zoneId1);
}
}
Instant
常用方法
-
static Instant now()
- 获取当前时间的Instant对象(标准时间)
-
static Instant ofXxx(long epochMills)
- 根据(秒/毫秒/纳秒)获取Instant对象
-
ZoneDateTime atZone(ZoneId zone)
- 指定时区
-
boolean isXxx(Instant otherInstance)
- 判断系列的方法
-
Instant minusXxx(long millisTosubtract)
- 减少时间系列的方法
-
Instant plusXxx(long millisTosubtract)
- 增加时间系列的方法
范例
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Test{
public static void main(String[] args){
//1.获取当前时间的Instant对象(标准时间)
Instant instant1=Instant.now();
System.out.println(instant1);
//2.根据(秒/毫秒/纳秒)获取Instant对象
//毫秒
Instant instant2=Instant.ofEpochMilli(0L);
System.out.println(instant2);
//秒
Instant instant3=Instant.ofEpochSecond(1L);
System.out.println(instant3);
//纳秒
Instant instant4=Instant.ofEpochSecond(1L,1000000000L);
System.out.println(instant4);
//3.指定时区
ZonedDateTime zonedDateTime=Instant.now().atZone(ZoneId.of("Asia/Shanghai"));
System.out.println(zonedDateTime);
//4.判断
//判断调用者是否在前
System.out.println(instant2.isBefore(instant3));
//判断调用者是否在后
System.out.println(instant2.isAfter(instant3));
//5.减少
System.out.println(instant3);
Instant instant5=instant3.minusSeconds(1L);
System.out.println(instant5);
//增加
Instant instant6=instant3.plusSeconds(1L);
System.out.println(instant6);
}
}
/*
2023-03-13T00:38:10.652Z
1970-01-01T00:00:00Z
1970-01-01T00:00:01Z
1970-01-01T00:00:02Z
2023-03-13T08:38:10.723+08:00[Asia/Shanghai]
true
false
1970-01-01T00:00:01Z
1970-01-01T00:00:00Z
1970-01-01T00:00:02Z
*/
ZoneDateTime
常用方法
-
static ZoneDateTime now()
- 获取当前时间的ZoneDateTime对象
-
static ZoneDateTime ofXxx(long epochMilli)
- 获取指定时间的ZoneDateTime对象
-
ZoneDateTime withXxx(时间)
- 修改时间系列的方法
-
ZoneDateTime minusXxx(时间)
- 减少时间系列的方法
-
ZoneDateTime plusXxx(时间)
- 增加时间系列的方法
范例
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Test{
public static void main(String[] args){
//1.获取当前时间的ZoneDateTime对象
ZonedDateTime now=ZonedDateTime.now();
System.out.println(now);
//2.获取指定时间的ZoneDateTime对象
ZonedDateTime time=ZonedDateTime.of(2023,10,1,11,12,12,0, ZoneId.of("Asia/Shanghai"));
System.out.println(time);
Instant instant=Instant.ofEpochMilli(0L);
ZoneId zoneId=ZoneId.of("Asia/Shanghai");
ZonedDateTime time1=ZonedDateTime.ofInstant(instant,zoneId);
System.out.println(time1);
//3.修改时间系列的方法
ZonedDateTime time2=time1.withYear(2000);
System.out.println(time2);
//4.减少时间系列的方法
ZonedDateTime time3=time2.minusYears(1);
System.out.println(time3);
//5.增加时间系列的方法
ZonedDateTime time4=time3.plusYears(1);
System.out.println(time4);
}
}
/*
2023-03-13T09:02:50.141+08:00[Asia/Shanghai]
2023-10-01T11:12:12+08:00[Asia/Shanghai]
1970-01-01T08:00+08:00[Asia/Shanghai]
2000-01-01T08:00+08:00[Asia/Shanghai]
1999-01-01T08:00+08:00[Asia/Shanghai]
2000-01-01T08:00+08:00[Asia/Shanghai]
*/
SimpleDateFormat类
常用方法:
- static DateTimeFormatter ofPattern(格式)
- 获取格式对象
- String format(时间对象)
- 按照指定方式格式化
- parse(“解析字符串”,格式化对象)
范例:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Test{
public static void main(String[] args){
ZonedDateTime zonedDateTime= Instant.now().atZone(ZoneId.of("Asia/Shanghai"));
DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH-dd-ss EE a");
System.out.println(dateTimeFormatter.format(zonedDateTime));
}
}
/*
2023-03-13 09-13-33 星期一 上午
*/
Calender
日历类
- LocalDate:年,月,日
- LocalTime:时,分。秒
- LocalDateTime:年,月,日,时,分,秒
常用方法:
- static XXX now()
- 获取当前时间的对象
- static XXX of(…)
- 获取指定时间的对象
- LocalDateTime转LocalDate和LocalTime
- toLocalDate()
- toLocalTime()
- get开头的方法
- 若是LocalDate,获取日历中的年,月,日
- 若是LocalTime,获取日历中的时,分,秒
- 若是LocalDateTime,获取日历中的年,月,日,时,分,秒
- isBefore,isAfter,equals
- 比较两个LocalDate
- with开头的
- 修改时间系列的方法
- minus开头的
- 减少时间系列的方法
- plus开头的
- 增加时间写的方法
工具类
- Duration:用于计算两个"时间"间隔,秒,微秒
- Period:用于计算两个“日期”间隔,年,月,日
- ChronoUnit:用于计算两个“日期”间隔,所有单位
包装类
包装类基本数据类型对应的对象
自动装箱:把基本数据类型自动转换成对应的包装类
自动拆箱:把包装类自动变成对象的基本数据类型
对应关系:
- byte-Byte
- short-Short
- char-Character
- int-Integer
- long-Long
- float-Float
- double-Double
- boolean-Boolean
使用方法:
不需要new和调用方法,直接赋值即可。
例:
public class Test{
public static void main(String[] args){
Integer i1=10;
int i=i1;
Integer i2=i;
Integer i3=i1+i2;
System.out.println("i1="+i1);
System.out.println("i2="+i2);
System.out.println("i3="+i3);
System.out.println("i="+i);
}
}
/*
i1=10
i2=10
i3=20
i=10
*/
注:判断自动撞箱范围在-128-127之间
- 若在:不会创建新的对象。而是从底层数组中直接获取
- 不在:重新new出新的integer对象
Integer成员方法
- public static String toBinaryString(int i)
- 得到二进制
- public static String toOctalString(int i)
- 得到八进制
- public static String toHexString(int i)
- 得到十六进制
- public static int parseInt(String s)
- 将字符串类型的整数转成int类型的整数
范例:
public class Test{
public static void main(String[] args){
System.out.println(Integer.toBinaryString(100));
System.out.println(Integer.toOctalString(100));
System.out.println(Integer.toHexString(100));
System.out.println(Integer.parseInt("123")+123);
}
}
/*
1100100
144
64
246
*/
注:
- 在类型转换的过程中,括号里的数字只能是数字,否则就会报错。
- 包装类中,除了Character外都有对应的** 包装类.parseXxx**的方法进行类型转换
- 在Scanner中,若我们使用next,nextInt,nextDouble在接收数据时,遇到空格,回车,制表符会停止接收,但若使用nextLine,则遇到回车才停止,所以以后尽量统一使用nextLine,用完之后再用包装类.parseXxx转换。